I have a string containing numbers and different mathematical operators. How can I parse this string from var str = "123+45-34";
an convert it to an array
var arr = [123, '+', 45, '-',34];
I have a string containing numbers and different mathematical operators. How can I parse this string from var str = "123+45-34";
an convert it to an array
var arr = [123, '+', 45, '-',34];
It looks like you want to split your string on word boundaries:
var str = "123+45-34";
console.log(str.split(/\b/));
You could use a different approach with an operator object, which could be usefull for calculating the value later.
function split(s) {
var a = s.split(''),
i = 1;
while (i < a.length) {
if (!(a[i - 1] in operators || a[i] in operators)) {
a[i - 1] += a.splice(i, 1)[0];
continue;
}
i++;
}
return a.map(function (b) {
return b in operators ? b : +b;
});
}
var operators = { '+': true, '-': true },
str = "123+45-34+1e13";
console.log(split(str));
One approach would be to split the string using a regex and then convert the parts into numbers where possible:
var str = "123+45-34";
var matches = str.match(/(\d+|\+|-|\/|\*)/g);
console.log(matches); // ["123", "+", "45", "-", "34"]
var asNumbers = matches.map(function(match) {
return +match || match
})
console.log(asNumbers); // [123, "+", 45, "-", 34]
This code tries to traverse through the string.Each charecter is appended into a newstring,until + or - is found,once they are found string formed till now will be pushed into newarray and special charecter either + or - is also pushed into newarray and again this process continues till the end of the string
Ex:123+
it traverses the string. first my newString ="1" ,then newString="12" finally newString="123" as soon as + is found ,it pushes newString into newarray.now newArray is ["123" ] and '+' should also be pushed ,now array becomes ["123","+"].this process continues
Here i have taken into consideration of special charecters as only + and -
var str="123+45-34";
var newarr=[];
var newStr="";
for(var index=0;index<str.length;index++){
if(str[index]!='+'&& str[index]!='-')
newStr+=str[index];
else{
newarr.push(newStr);
newarr.push(str[index]);
newStr="";
}
}
console.log(newarr);
Hope this helps