What will be the best way using javascript regular expression to get numbers out of text.. e.g.... I have "$4,320 text/followme" and I want to get 4320 out of this. However I want to avoid numbers after first occourance of an alphabet or any non alphabet other than a comma ','
so that if i have $4,320 t234ext/followme it will still return me 4320. The input will always have $ sign at the beginning
so the regular expression should return
$4,320 text/followme returns 4320
$4,320 t3444ext/followme return 4320
$4,320 /followme return 4320
$4320 text/followme return 4320
$4320 t3444ext/followme return 4320
$4320 /follow4me return 4320
string.split(/ /)[0].replace(/[^\d]/g, '')
The simplest regular expression you're possibly looking for is \D
(any character that's not a numeral. There's a few of these "negated" expressions -- \d
matches a numeral, \D
matches non-numerals. \w
matches "word" characters (alphanumeric plus the underscore), \W
matches non-numeric. \s
matches whitespace, \S
matches non-whitespace characters).
So:
str = '$4,320 text/folowme';
number = str.replace(/\D/g,'');
should yield '4320' inside of number. The 'g' is important. It says do a global search/replace for all instances of that regex. Without it, you'll just lose the dollar sign. :)
Note that if you've got negative numbers or rationals (which can have two non-numeric characters in their representation, '-' and '.'), your problem gets a little bit harder. You could do something like:
number = str.replace(/[^-.0-9]/g,'');
Which will work as long your numbers are well formed -- as nobody does anything crazy like '4-5.0-9aaaa4z.2'.
To be safe, you could run that list bit through parseInt
or parseFloat
:
number = parseFloat(str.replace(/[^-.0-9]/g,''));
UPDATE
I spaced the requirement to avoid including subsequent numbers. If whitespace reliably delimits the end of the number you want, as it does in the examples, you could add a space or \s to the negated character class on that last example I gave, so it'd be something like this:
number = parseFloat(str.replace(/[^-.0-9\s]/g,''));
and it'll strip out the extra numbers just fine.
UPDATE 2
After thinking about this for a bit, using parseFloat
means that you don't have to strip out everything -- just all the non-numeric characters before the number you want, and commas. So we can break this into two simpler regexes (and probably faster, especially since one of them is non-global). And then parseFloat
will discard trailing non-numeric input for you.
number = parseFloat(str.replace(/,/g,'').replace(/^[^-0-9]*/,''));
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