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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With