How to find a number in a string using JavaScript?

javascript, regex

Solution

Use a regular expression.

const r = /\d+/;
const 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:

const r = /\d+/;

is equivalent to:

const 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:

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

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

Problem

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?

Original source