If i add a value to a string name i want to get the length of the string not the length of the string name.
var wordlist3 = "ABC";
var xc = 3;
var num_words = ('wordlist' + xc).length;
With the above code i get wordlist3.length as 9 when it should be 3. How do i append a string name so it references the length of the string in wordlist3, without making it a global var?
Im expecting the answer:
num_words = 3
not
num_words = 9
The best way to do this would be to put your word list in arrays.
var wordlist = [];
wordlist[0] = 'ABC';
wordlist[0].length;//3
You can also use the window object to get at it, if it's in the correct scope
window['wordlist' + xc].length;//gives 3
Use this for that:
eval('wordlist' + xc).length;
Related
Link - split and remove first 3 array.
offerlink variable will have multiple urls. But, /content/revamp/en will remain same for all links. Have to remove this from the path name.
offerlink2 - works as expected. But, offerLink1 also getting result by excluding /hotels/india. this is required for this url.
Same code have to work for both offerlInk1 and offerLink2.
JS:
var offerlink = /content/revamp/en/hotels/india/offers/purchase.html
var offerLinkSplit = $offerLink.replace(/\.\w+$/, '').split('/');
var offerLinkTrim = $offerLinkSplit.slice(-2).join('/');
getting output (Wrong) = /offers/purchase
Needed output = /hotels/india/offers/purchase
If below link means /content/revamp/en/offers/quick-deal.html
correct output = /offers/quick-deal
Try using slice(4) to extract past the 4th / in your input:
var $offerLink1 = '/content/revamp/en/hotels/india/offers/purchase.html'
var offerLinkSplit1 = $offerLink1.replace(/\.\w+$/, '').split('/');
var offerLinkTrim1 = '/' + offerLinkSplit1.slice(4).join('/');
console.log(offerLinkTrim1);
Note that strings need to be enclosed in delimiters, and you need to use consistent variable names.
A regular expression alone might be better here, though: match 3 repetitions of /<anything but />, and replace with the empty string:
var $offerLink1 = '/content/revamp/en/hotels/india/offers/purchase.html';
var $offerLink2 = '/content/revamp/en/offers/quick-deal.html';
const re = /(?:\/[^/]+){3}/;
console.log(
$offerLink1.replace(re, ''),
$offerLink2.replace(re, '')
);
var offerlink = /content/revamp/en/hotels/india/offers/purchase.html
var offerLinkSplit = $offerLink.replace(/\.\w+$/, '').split('/');
var offerLinkSplitLength = offerLinkSplit.length;
var offerLinkTrim = offerLinkSplit.slice(4,offerLinkSplitLength).join('/');
If /content/revamp/en always remains the same, simply take the substring
var offerlink1 = '/content/revamp/en/hotels/india/offers/purchase.html';
var removeText = '/content/revamp/en';
console.log(offerlink1.substring(removeText.length))
slice(-2) only takes the last 2 elements.
To remove the first three use slice(3).
See docs for more information.
var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];
I have a rather specific problem.
I'm using ng-csv, and because it doesn't support nested arrays, I'm turning an array into a string.
Something like this:
[
{"name":"Maria","chosen":false},
{"name":"Jenny","chosen":false},
{"name":"Ben","chosen":false},
{"name":"Morris","chosen":false}
]
Turns into:
$scope.var = "Maria, Jenny, Ben, Morris"
My problem is that when I was using the array I was able to count the number of names in the array (which I need for UI reasons), but with the string it gets tricky.
Basically, I cannot count the number of words because some names might include last name, but I thought I could count commas, and then add 1.
Any pointers on how to do just that?
If you need names itself - you may use method split of String class:
var str = "Maria, Jenny, Ben, Morris";
var arr = str.split(','); // ["Maria", " Jenny", " Ben", " Morris"]
var count = arr.length; // 4
var str = "Maria, Jenny, Ben, Morris";
var tokens = str.split(",");
The number of tokens should be captured in tokens.length. Alternately, if you don't actually need to work with the tokens directly:
var nameCount = str.split(",").length;
Why not use regex?
var _string = "Mary, Joe, George, Donald";
_string.match(/,/g).length // 3
I have a single input where I can submit text as such: name, score
I'm parsing the results so that the name is stored in a variable as a string and the score is stored in a variable as an integer. This looks quite clunky. Is there a way to parse the text without requiring five separate variables?
// capture submitted string result
var namescore = document.getElementById('namescore').value;
// split it at the comma
var parts = namescore.split(", ");
// make sure first part is a string
var pname = parts [0].toString();
// convert score string to integer
var scoreString = parts [1];
var score = parseInt(scoreString, 10);
Here, two variables:
var parts = document.getElementById('namescore').value.split(", ");
var result = {
name: parts[0],
score: parseInt(parts[1], 10)
}
You can access the score like that:
result.score
And the name:
result.name
Two could be eliminated easily even in your code:
// split it at the comma
var parts = document.getElementById('namescore').value.split(", ");
// make sure first part is a string
var pname = parts[0].toString();
// convert score string to integer
var score = parseInt(parts[1], 10);
Or you don't really need pname and score, if you only use them once, then you can use what's on the right side of the equation there. Then you're left only with 1 variable: parts
You do not, by any means, need to introduce a variable for every operation in that manner:
// capture submitted string result
var parts = document.getElementById('namescore').split(", ");
// make sure first part is a string
var pname = parts[0].toString();
// convert score string to integer
var score = parseInt(parts[1], 10);
The above code does the exact same things as your code. You could skip the .toString call: the result of splitting a string will always be an array of strings.
Any reason not to leave them as members of the parts array?
// capture submitted string result
var namescore = document.getElementById('namescore').value;
// split it at the comma
var parts = namescore.split(", ");
parts[0] = parts[0].toString();
parts[1] = parseInt( parts[1], 10 );
Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.