Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to get the number from the end of a string

People also ask

How do you find the number at the end of a string?

To get the number from the end of a string, call the match() method, passing it the following regular expression [0-9]+$ . The match method will return an array containing the number from the end of the string at index 0 .

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


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

RegEx:

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

String manipulation:

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