9

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.

6 Answers 6

20

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

Sign up to request clarification or add additional context in comments.

Comments

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

or

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

1 Comment

You forgot to close the string "mr.
4

Why not simply:

-mr(\d+)

Then getting the contents of the capture group?

Comments

2

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"

4 Comments

Wow, almost identical solution, practically at the same time. Cheers :).
Are you sure you want to test match[1]? This will be evaluated to false if it’s 0.
@Gumbo: It wont evaluate false, because the matches are Strings not Numbers, it will only evaluate to false if match[1] is an empty string.
Heh, it would evaluate false if it would be a string containing '0' only in PHP, hence the confusion, probably. That's a stupid thing to do, btw.
1

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;

2 Comments

There's no need to include the first .* and the hyphen needs no escaping. This works as well: "-mr(.*)". But the .* is dangerous: if there's a lot more text after "-mr" the .* will "eat" it. Of course, the OP wasn't really clear about what text could come after "-mr".
That's a good point. I was assuming that the OP would want everything after the "-mr". I modified the code to remove the escape before the hyphen and restrict the subexpression to digits. I escape everything out of habit more than anything else. :)
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.