How to find a number in a string using JavaScript?

Suppose I have a string like - "you can enter maximum 500 choices". I need to extract 500 from the string.

The main problem is the String may vary like "you can enter maximum 12500 choices". So how to get the integer part?


Use a regular expression.

var r = /\d+/;
var s = "you can enter maximum 500 choices";
alert (s.match(r));

The expression \d+ means "one or more digits". Regular expressions by default are greedy meaning they'll grab as much as they can. Also, this:

var r = /\d+/;

is equivalent to:

var r = new RegExp("\d+");

See the details for the RegExp object.

The above will grab the first group of digits. You can loop through and find all matches too:

var r = /\d+/g;
var s = "you can enter 333 maximum 500 choices";
var m;
while ((m = r.exec(s)) != null) {
  alert(m[0]);
}

The g (global) flag is key for this loop to work.


var regex = /\d+/g;
var string = "you can enter maximum 500 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches);


References:

    http://www.regular-expressions.info/javascript.html

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp


var str = "you can enter maximum 500 choices";
str = str.replace(/[^0-9]/g, "");
console.log(str); // "500"