Hawkeye Hawkeye - 3 months ago 10
Javascript Question

How to get numbers each side of a symbol

How would I get the numbers on each side of a symbol using Javascript?

Ex. Get

14
and
21
from
extra chars 14 + 21 extra chars
or
extra chars 14+21 extraChars
.

I had an idea for 14 + 21 using
var ary = 'extra chars 14 + 21 extra chars'.split(' ')
and
indexOf('+')+1
and
indexOf('+')-1
but this does not work for
14+21
.

How would I do this so that it would also support multiple symbols?

Answer

You can use regular expressions something like that...

var re = /(\d*) *\+ *(\d*)/g; 
var str = 'extra chars 14 + 21 extra chars';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    console.log(m[0]);
    console.log(m[1]);
    console.log(m[2]);
}