Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript match substring after RegExp

I have a string that look something like

something30-mr200

I would like to get everything after the mr (basically the # followed by mr) *always there is going to be the -mr

Any help will be appreciate it.

like image 731
Mike Avatar asked Oct 14 '09 20:10

Mike


3 Answers

You can use a regexp like the one Bart gave you, but I suggest using match rather than replace, since in case a match is not found, the result is the entire string when using replace, while null when using match, which seems more logical. (as a general though).

Something like this would do the trick:

function getNumber(string) {
    var matches = string.match(/-mr([0-9]+)/);
    return matches[1];
}
console.log(getNumber("something30-mr200"));
like image 134
treznik Avatar answered Oct 10 '22 04:10

treznik


var result = "something30-mr200".split("mr")[1];

or

var result = "something30-mr200".match(/mr(.*)/)[1];
like image 21
Kamarey Avatar answered Oct 10 '22 05:10

Kamarey


Why not simply:

-mr(\d+)

Then getting the contents of the capture group?

like image 32
toolkit Avatar answered Oct 10 '22 05:10

toolkit