63

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.

alex
  • 479,566
  • 201
  • 878
  • 984
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

2 Answers2

104

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);
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    Tip: It is more efficient to use `[0-9]` than it is to use `\d` . See https://stackoverflow.com/questions/16621738 – Josh Withee Dec 26 '17 at 16:11
  • 3
    @Marathon55 Very well might be the case, but I'd still use `\d` myself (unless it became a performance bottleneck) – alex Jan 09 '18 at 10:37
15

RegEx:

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

String manipulation:

var str = "example12",
    prefix = "example";
parseInt(str.substring(prefix.length), 10);
jensgram
  • 31,109
  • 6
  • 81
  • 98