Kyle.S Kyle.S -3 years ago 141
Javascript Question

JavaScript regex with this symbol "^" need to grab all numbers surrounding it

I need to grab all digits before and after the "^" symbol, until it runs into any characters other than a digit stop. I tried this with a for loop but I'm having a little bit of trouble.

function equal(e) {
var last = [],
string = values.innerHTML;
for(var i = 0; i < string.length; i++) {
if(/[\^]/.test(string[i])) {
last.push(i);
}
}

var storage = [],
counter = 1,
left = 0,
right = 0,
found = true,
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '(', ')', '.', '^'],
fullArr = [];

for(var i = 0; i < last.length; i++) {
while(found) {
if(nums.indexOf(string[last[i]+counter]) != -1 && nums.indexOf(string[last[i]-counter]) != -1) {
right++;
left++;
} else if(nums.indexOf(string[last[i]-counter]) != -1) {
left++;
} else if(nums.indexOf(string[last[i]+counter]) != -1) {
right++
}
if(nums.indexOf(string[last[i]+counter]) == -1 && nums.indexOf(string[last[i]-counter]) == -1) {
storage.push([left, right]);
counter = 1;
left = 0;
right = 0;
break;
}
counter++;
}
}

for(var i = 0; i < last.length; i++) {
console.log(last[i] - storage[i][0], last[i] + (storage[i][1]+1));
fullArr.push(string.slice(last[i] - storage[i][0], last[i] + (storage[i][1]+1)));
}
console.log(fullArr);
values.innerHTML = eval(values.innerHTML);
removeClass(e.target, 'special');


}

Answer Source
var mystr="123^345"+
"abc12^3456def\n"+
"abc^345\n"+
"^345\n"+
"345^\n"+
"345^def";
X=/([\d\.]+)?\^(\d+\.)?/img
while (mat=X.exec(mystr)){
    console.log( mat[1]+":"+mat[2])
}

Output

123:345
12:3456
undefined:345
undefined:345
345:undefined
345:undefined

Hope you can do the needful for undefined above.

Working example here.

UPDATE
I just noticed that you are using this for calculator then it would be as below:-

X=/([\d\.]+)\^([\d\.]+)/img
while (mat=X.exec(mystr)){
    console.log( mat[1]+":"+mat[2])
}

Output

123:345
12:3456

Working example here.


UPDATE2

X=/([\d\.]+)\^([\d\.]+)/img
while (mat=X.exec(mystr)){
    mystr=mystr.replace(mat[0],(Number(mat[1])**Number(mat[2])).toString())
}
console.log(mystr)

Working example here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download