I have a sting like this:
"a;b;x"
and I want to convert it to
"a"; "b"; "x"
You can use map to to return an array that you join at the end of the operation.
The map operation merely checks to see if the current element is the last in the array. If it is, don't append a semi-colon, then return the transformed element.
var output = str.split(';').map(function (el, i, arr) {
return i === (arr.length - 1) ? '"' + el + '"' : '"' + el + '";'
}).join(' ');
DEMO
Or perhaps the slightly easier to understand:
var output = str.split(';').map(function (el, i, arr) {
var end = i === (arr.length - 1) ? '' : ';';
return '"' + el + '"' + end;
}).join(' ');
you are searching for split() method
http://www.w3schools.com/jsref/jsref_split.asp
var str = "a;b;x";
var str_split = str.split(";");
var result = '"';
for (var i = 0; i < str_split.length; i++) {
result += str_split[i] + '"; "' }
result = result.substring(0, result.length - 3);
have a nice day ;)
This regexp wraps each letter by quote symbol and adding space symbol with new ";".And removes from end last "; "
var result = "a;b;x".replace(/(\w)(;)*/g,'"$1"; ').replace(/;\s+$/g,"");
console.log(result) // '"a"; "b"; "x"'
$1 - is letter
Related
I want an eval() function which will calculate brackets as same as normal calculations but here is my code
var str = "2(3)+2(5)+7(2)+2"
var w = 0;
var output = str.split("").map(function(v, i) {
var x = ""
var m = v.indexOf("(")
if (m == 0) {
x += str[i - 1] * str[i + 1]
}
return x;
}).join("")
console.log(eval(output))
Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.
Obligatory "eval() is evil"
In this case, you can probably parse the input. Something like...
var str = "2(3)+2(5)+7(2)+2";
var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b);
console.log(out);
while( out.indexOf("+") > -1) {
out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b));
}
console.log(out);
You can do it much simplier, just insert '*' in a right positions before brackets
var str = "2(3)+2(5)+7(2)+2"
var output = str.replace(/\d\(/g, v => v[0] + '*' + v[1])
console.log(eval(output))
Can someone please help me to write a JS method which takes a String value like
/Content/blockDiagram/0/bundle/0/selectedBundle
/Content/blockDiagram/1/bundle/1/selectedBundle
/Content/blockDiagram/0/bundle
and convert it to
/Content/blockDiagram[1]/bundle[1]/selectedBundle
/Content/blockDiagram[2]/bundle[2]/selectedBundle
/Content/blockDiagram[1]/bundle
It is basically taking the number in the path and increment it by 1 and then changing the structure of the string.
My attempt
function setReplicantPartListOptions(list) {
list = "/" + list;
var index = list.lastIndexOf("/");
var tempString = list.substring(0, index);
var index2 = tempString.lastIndexOf("/");
var initialString = list.substring(0, index2);
var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
var lastString = list.substring(index, list.length);
list = initialString + "[" + middlevalue + "]" + lastString;
return list;
}
simple regular expression with capture group with replace
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
var next = +num + 1; // convert string to number and add one
return "[" + next + "]"; //return the new string
})
console.log(updated)
String.replace(RegExp, callback(match, contents)) is the callback version of String.replace().
In my case, the first parameter of callback function is the result/match. It takes the match and converts it to number using + operator, and then increment it by one. Finally, I add [ ] around the value and return it!
let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)
On the first alert(array[0]) I get a full word. On the next alert after the loop, I get only a character with each reference. I found a similar question on here, but there wasn't an answer with it.
var listNumbers = document.getElementById("someNames").getElementsByTagName("li");
for(var i = 0; i<listNumbers.length; i++) {
z = (listNumbers[i].innerHTML);
array = z.split(" ");
alert(array[0]);
firstArray = firstArray + '"' + array[0] + '"' + ", ";
lastArray = lastArray + '"' + array[1] + '"' + ", ";
phoneArray = phoneArray + '"' + array[2] + '"' + ", ";
}
alert(firstArray[1]);
You are building your firstArray variable as a string, not an array. When you access a string with [0], you will get the character at that position in the string, not a whole word.
If you want to be able to access words, you need to declare it as an array and use .push() to add words to it.
var listNumbers = document.getElementById("someNames").getElementsByTagName("li");
var arrayOfFirstNames = [];
var arrayOfLastNames = [];
var arrayOfPhoneNumbers = [];
for(var i = 0; i<listNumbers.length; i++) {
z = (listNumbers[i].innerHTML);
array = z.split(" ");
alert(array[0]);
arrayOfFirstNames.push('"' + array[0] + '"');
arrayOfLastNames.push('"' + array[1] + '"');
arrayOfPhoneNumbers.push('"' + array[2] + '"');
}
alert(arrayOfFirstNames[0]);
I don't have your HTML so I havn't tested this code, but it should do the job if all you want is 3 arrays of first names, last names and phone numbers that you can access using square bracket notation.
Having trouble coming up with code doing this.
So for example here is my string.
var str = "Hello how are you today?";
How would I manipulate this string to return the position of the first letter of each word using a loop?
this will give you the result with less complicated code and a single loop
function foo(str) {
var pos = [];
var words = str.split(' ');
pos.push(1);
var prevWordPos;
for (var i = 1; i < words.length; i++) {
prevWordPos = pos[i - 1] + words[i - 1].length;
pos.push((str.indexOf(words[i], prevWordPos) + 1));
}
return pos;
}
You should search for a question before asking it in case it's already been asked and answered.
Get first letter of each word in a string, in Javascript
You can use a regexp replace passing a function instead of a replacement string, this will call the function for each match:
str.replace(/[^ ]+/g, function(match, pos) {
console.log("Word " + match + " starts at position " + pos);
});
The regexp meaning is:
[^ ]: anything excluding space
+: one or more times
"g" option: not only first match, but each of them
in other words the function will be called with sequences of non-spaces. Of course you can define what you consider a "word" differently.
Here is a Solution with two Loops, i hope that is close enough ;)
var starts = [];
var str = "How are you doing today?";
//var count = 0;
var orgStr = str;
while (str.indexOf(" ") > 0) {
if (starts.length > 0) {
starts.push(starts[starts.length - 1] + str.indexOf(" ") +1);
} else {
starts.push(1);
starts.push(str.indexOf(" ") +2);
//alert(str);
}
str = str.substring(str.indexOf(" ") + 1);
}
for (var i = 0; i < starts.length; i++) {
alert(starts[i] + ": " + orgStr.substring(starts[i]-1,starts[i]))
}
Easiest would be to search a regular expression \b\w and collect match.start() match.index for each match. Loop while there's matches.
EDIT: wrong language. lol.
In the loop below, how can I remove the comma from the latt key in the loop?
var result = 'These are the results: ';
jQuery.each(item['keyterms']['terms'],function(i,kw){
for (key in keywords){
sep = ',';
if (keywords[key] > 5) result += '<span>' + key + sep + '</span>';
}}
Instead of inserting coma inside loop you can use standard javascript function JOIN
var results = Array();
for (key in keywords){
if (keywords[key] > 5) results.push('<span>' + key + '</span>');
}
var message = 'These are the results: ' + results.join(',');
Simple - instead of putting the separator after the key, put it before, and skip the first element (it's much easier to know when the element is first, than when it's last):
var first = true;
var result = '';
for (key in keys) {
var sep = first ? '' : ', ';
result += sep + key;
first = false;
}
note that for joining strings in JS the arrays join(separator) method is faster than the + operator. So I recommend Nazariy's solution. with a small change:
var result = Array();
for (key in keywords){
if (keywords[key] > 5) result.push(['<span>', key, sep, '</span>'].join(''));
}}
result = result.join(',');
If you're just concerned about how to remove the last separator then this should work:
jQuery.each(item['keyterms']['terms'],function(i,kw){
for (key in keywords){
sep = ',';
if (keywords[key] > 5) result += '<span>' + key + sep + '</span>';
}}
result = result.substring(0, result.length - (sep+"</span>").length) + "</span>");
Otherwise, Nazariy's join solution is a better way to create the whole string.
Why do you even add it?
var result = 'These are the results: ';
jQuery.each(item['keyterms']['terms'],function(i,kw){
var sep = '';
for (key in keywords){
if (keywords[key] > 5) result += '<span>' + sep + key + '</span>';
sep = ',';
}}