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?
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?
I like @jesterjunk answer, however, a number is not always just digits. Consider those valid numbers: "123.5, 123,567.789, 12233234+E12"
So I just updated the regular expression:
You can also try this :
If You want to learn more about regex here are some links:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm
Use a regular expression.
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:is equivalent to:
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:
The
g
(global) flag is key for this loop to work.