Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
Devi Avatar asked Oct 26 '09 05:10

Devi


1 Answers

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.

like image 177
cletus Avatar answered Oct 08 '22 09:10

cletus