How can I get the first "word" out of these strings?
/User/Edit/
/Admin/Edit/2
/Tags/Add
I should get User, Admin, Tags, etc
http://jsfiddle.net/RV5r2/1/
as simple as this. since you split it up in an array, just return the first element:
return ar[1];
and youre ready to go ;)
or you could reverse() first and the pop() :D but this migth be a bit odd. just be sure you check if the array key [1] is set! by
return (typeof ar[1] !== 'undefined') ? ar[1] : '';
Or again:
return ar.slice(1,2);
I would recommend that you change a bit the logic in your lastWord method (note: lastWord is not a good name for this method - maybe firstWord?) to take in account paths/strings which don't start with "/" and paths that don't contain "/"
function lastWord(subject)
{
var ar = subject.split("/");
if(ar.length >= 2)
{
//we have at least one / in our string
if(ar[0] !== "") {
//the string doesn't start with /
return ar[0];
}
else {
//if the strings starts with / then the ar[0] will be ""
return ar[1];
}
}
else {
//we return an empty string if the input was not valid, you could handle this differently
return "";
}
}
This way :
"/some/amazing/sentence" will return "some"
"some/amazing/sentence" will return "some"
"someamazingsentence" will return ""
Related
So I have a function that checks if the last character in a string is an arithmetic operator(+,-,*,/), and if it is it should immediately return from the function. If not, the subtract sign should be appended to the string. However, only the second case seems to be occurring and I can't figure out why. If anyone could provide some insight I would be very appreciative.
$("#subtract").click(function () {
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
var signs=["+","-","*","/"];
var charpos=sliced.charAt(sliced.length -1);
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
else {
var newdisplay=sliced + "-";
$("#display").text(newdisplay);
}
});
You're slicing the input which is removing the last character, then using charAt and getting the second to last character.
var original=$("#display").text(); // "foobar"
var sliced=original.slice(0,original.length - 1); // "fooba"
var charpos=sliced.charAt(sliced.length -1); // "a" -- we lost the "r"
You only need to call charAt and work with the last character (or, if you prefer slice, it's able to accept a negative number and backtrack the string).
Secondly, since signs is an array, you can use indexOf over checking each element. e.g.
var original = $('#display').text();
var signs = ["+","-","*","/"];
var lastChar = original.slice(-1); // OR original.charAt(original.length - 1);
// Check for the lastChar in the signs array
if (signs.indexOf(lastChar) != -1){ // -1 == not found
return; // short exit
}
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
the second line gets rid of the last character in your string. so you're not even able to check what that was. just get rid of it and change the first line to
var sliced=$("#display").text();
and everything should work fine
Instead of
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
try
if ($.inArray(charpos, signs) > -1) {
return;
}
First of all, never enumerate items from an array in such a fashion - it's easy to miss items that way. Secondly, exact instance comparison (===) won't fire, unless you compared exact same strings.
Besides, consider revising how you extract the last character.
This task requires that you write a function that takes two arguments. The first argument is a string called str and the second argument is a string that our target ending named target. The task is to verify that the ending of str is identical to the target ending. The instructions indicate to use the .substr() method to compare the endings to the targets. The problem I have is that there are going to be multiple starting points and length arguments for the .substr method since the target endings can be of variable length. Take a look at my attempt to solve this issue and please direct me in the right path.
function end(str, target) {
var start = str.length - (target.length - 1);
if(str.substr(start, str.length) == target){
return true;
} else {
return false;
}
}
end('Bastian', 'n');
EDIT
As #torazaburo said. The correct answer Is:
function end(str, target) {
return target === str.substr(str.length - target.length);
}
Because The string does end with a null string
ORIGINAL ANSWER
function end(str, target) {
return target.length > 0 && target === str.substr(str.length - target.length);
}
http://jsfiddle.net/tqsx0gLa/2/
From Comments:
This code is setting up a logical comparison using the && operator. The left side target.length > 0 should always return true with a valid target input. The left side is setting target equal to the substr starting at the point located by taking the str.length (the position at the far right of the str) and subtracting the target length (to arrive at the start point of our substring). There is no need for an end point input because the substring will run to the end of str.
Here is a easy solution :
function confirmEnding(str, target) {
var result;
//getting the last string depend on target length
var last = str.substring(str.length - target.length);
//checking the last string with the target
if(last === target){
result = true;
} else {
result = false;
}
return result;
}
function end(str, target) {
var start = str.length - target.length;
if(str.substr(start) == target){
return true;
}
else {
return false;
}
}
You can also try this code.
The substring method can take a negative value to work from the end of the string. The solution to your problem is very simple:
function end (str, target) {
return str.substr(-target.length) === target;
}
end("simple is better", "better"); // returns true
// which is the same as writing
"simple is better".substr(-6) === "better" // true again
I find this simple:
function end(str, target) {
return str.substr(-target.length) == target;
}
I like your original answer, it is clean and easy to ready.
Try removing the -1 on line 2. This way it will return all of the target word in your substr.
function end(str, target) {
var start = str.length - (target.length);
if(str.substr(start) == target){
return true;
} else {
return false;
}
}
end ("He has to give me a new name", "name")
When the sub-string does not return a second argument, it will return from the number that is start to the end of the string.
function confirmEnding(str, target) {
var position = str.length - target.length; //get start position for our .substr method.....
if (str.substr(position, target.length == target){ // logical expression wich tell our method(.substr) from which position we need get information then we compare result with our "target" argument.
return true;
} else { return false; }
}
confirmEnding("Bastian", "n"); // true
My solution uses substr method that takes the length of the target and with minus gives us the last characters of the first string for comparison.
const confirmEnding = (str, target) => str.substr(-target.length) === target ?
true :
false;
Here you go:
const solution = (str, target) => str.endsWith(target);
The cleanest way.
`
function endSearch(str, ending){
// just on line to solve this problem
// endsWith() ==> string.endsWith('string search' , position = str.length['defalut value'])
return str.endsWith(ending)
}
console.log(endSearch('abc', 'bc')) // ture
console.log(endSearch('abc', 'a')) // false
console.log(endSearch('abc', 'x')) // false
`
I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?
There is a box that has a css background-image. By jQuery I want to check the value of this background-image, and if it contain a specific name then console.log("done").
Here is my jQuery code:
var bgName = $(".leftBox").css("background-image");
if (bgName.search("Z3Escd") == 0){
console.log("done");
}
// Z3Escd is the name of my file that it must check.
Unfortunately it does not work. DEMO http://jsfiddle.net/danials/qU8W7/
Any idea to find some certain characters in the string?
Use this
var bgName = $(".leftBox").css("background-image");
if (bgName.search("Z3Escd") != -1){
console.log("done");
}
You should check if bgName.search result is >= 0. That's because String.search returns index of start of searched substring, and -1 if substring was not found.
You use your search function wrong.
The result of bgName.search is the startindex of your provided string in the to search string.
The best method would be to check if the string endswith:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
var bgName = $(".leftBox").css("background-image");
if (bgName.endsWith ("Z3Escd")){
console.log("done");
}
I need to check to see if a variable is null or has all empty spaces or is just blank ("").
I have the following, but it is not working:
var addr;
addr = " ";
if (!addr) {
// pull error
}
If I do the following, it works:
if (addr) {
}
What I need is something like the C# method String.IsNullOrWhiteSpace(value).
A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:
function isEmptyOrSpaces(str){
return str === null || str.match(/^ *$/) !== null;
}
...then:
var addr = ' ';
if(isEmptyOrSpaces(addr)){
// error
}
* EDIT *
Please note that op specifically states:
I need to check to see if a var is null or has any empty spaces or for that matter just blank.
So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.
if (addr == null || addr.trim() === ''){
//...
}
A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).
You can use if(addr && (addr = $.trim(addr)))
This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.
Reference: http://api.jquery.com/jQuery.trim/
Old question, but I think it deservers a simpler answer.
You can simply do:
var addr = " ";
if (addr && addr.trim()) {
console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");
}
Simplified version of the above: (from here: https://stackoverflow.com/a/32800728/47226)
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
You can create your own method Equivalent to
String.IsNullOrWhiteSpace(value)
function IsNullOrWhiteSpace( value) {
if (value== null) return true;
return value.replace(/\s/g, '').length == 0;
}
isEmptyOrSpaces(str){
return !str || str.trim() === '';
}
When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:
function isNullOrWhiteSpace(str){
return str == null || str.replace(/\s/g, '').length < 1;
}
isEmptyOrSpaces(str){
return str === null || str.trim().length>0;
}
Try this out
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* #param {any} str string to be evaluated
* #returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
function isEmptyOrSpaces(str){
return str === null || str.match(/^[\s\n\r]*$/) !== null;
}
I use simply this and this works for me most of the time.
it first trim the white spaces and then checks the length.
if(value.trim().length === 0)
{
//code for empty value
}
Maybe it's easier this way
if (!addr?.trim()){
//error
}
Based on Madbreaks' answer, and I wanted to account for undefined as well:
function isNullOrWhitespace(str) {
return str == null || str.match(/^\s*$/) !== null;
}
Jest tests:
it('works for undefined', () => {
expect(isNullOrWhitespace(undefined)).toEqual(true);
});
it('works for null', () => {
expect(isNullOrWhitespace(null)).toEqual(true);
});
it('works for empty', () => {
expect(isNullOrWhitespace('')).toEqual(true);
});
it('works for whitespace', () => {
expect(isNullOrWhitespace(' ')).toEqual(true);
// Tab
expect(isNullOrWhitespace(' ')).toEqual(true);
});
You can try this:
do {
var op = prompt("please input operatot \n you most select one of * - / * ")
} while (typeof op == "object" || op == "");
// execute block of code when click on cancle or ok whthout input