var string = 'Our Prices are $355.00 and $550, down form $999.00';
How can I get those 3 prices into an array?
var string = 'Our Prices are $355.00 and $550, down form $999.00';
How can I get those 3 prices into an array?
Use match
with regex
as follow:
string.match(/\$\d+(\.\d+)?/g)
Regex Explanation
/
: Delimiters of regex
\$
: Matches $
literal\d+
: Matches one or more digits()?
: Matches zero or more of the preceding elements\.
: Matches .
g
: Matches all the possible matching charactersThis will check if there is a possible decimal digits following a '$'
The RegEx
That
|| []
is for no matches: it gives an empty array rather thannull
.Matches
$99
$.99
$9.99
$9,999
$9,999.99
Explanation
To match numbers like
.99
more easily I made the second number mandatory (\d+
) while making the first number (along with commas) optional (\d*
). This means, technically, a string like$999
is matched with the second number (after the optional decimal point) which doesn’t matter for the result — it’s just a technicality.