Mike
Mike

Reputation: 91

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.

Upvotes: 9

Views: 25684

Answers (6)

treznik
treznik

Reputation: 8134

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"));

Upvotes: 20

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828050

What about:

function getNumber(input) { // rename with a meaningful name 
    var match = input.match(/^.*-mr(\d+)$/);

  if (match) { // check if the input string matched the pattern
    return match[1]; // get the capturing group
  }
}

getNumber("something30-mr200"); // "200"

Upvotes: 2

Joe D
Joe D

Reputation: 3708

This may work for you:

// Perform the reg exp test
new RegExp(".*-mr(\d+)").test("something30-mr200");
// result will equal the value of the first subexpression
var result = RegExp.$1;

Upvotes: 1

toolkit
toolkit

Reputation: 50287

Why not simply:

-mr(\d+)

Then getting the contents of the capture group?

Upvotes: 4

Kamarey
Kamarey

Reputation: 11079

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

or

var result = "something30-mr200".match(/mr(.*)/)[1];

Upvotes: 4

Seb
Seb

Reputation: 25157

What about finding the position of -mr, then get the substring from there + 3?

It's not regex, but seems to work given your description?

Upvotes: 0

Related Questions