John John - 7 months ago 16
Javascript Question

catch string from a specific point

How can i catch the string right from the underscore?

I don't want the underscore to be part of the result.


the result should be:

this is a test


instead of
_this is a test


I want to solve this with regex, because i try to understand
different scenarios.



var re = /(?:_)(.*)/g;
var str = 'foo _this is a test';
var m;
m = re.exec(str)

document.write(m[0]);




Answer

Because you didn't just take the group 1 value. You take all of the Regex value instead. The code should be:

document.write(m[1]); // m[1] for taking group 1