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]*/,''));