regex to get the number from the end of a string

JavascriptRegex

Javascript Problem Overview


i have a id like stringNumber variable like the one as follows : example12 I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.

Javascript Solutions


Solution 1 - Javascript

This regular expression matches numbers at the end of the string.

var matches = str.match(/\d+$/);

It will return an Array with its 0th element the match, if successful. Otherwise, it will return null.

Before accessing the 0 member, ensure the match was made.

if (matches) {
    number = matches[0];
}

jsFiddle.

If you must have it as a Number, you can use a function to convert it, such as parseInt().

number = parseInt(number, 10);

Solution 2 - Javascript

RegEx:

var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);

String manipulation:

var str = "example12",
    prefix = "example";
parseInt(str.substring(prefix.length), 10);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaurabh KumarView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - JavascriptjensgramView Answer on Stackoverflow