Get all prices with $ from string into an array in Javascript

2.1k Views Asked by At
var string = 'Our Prices are $355.00 and $550, down form $999.00';

How can I get those 3 prices into an array?

3

There are 3 best solutions below

6
On BEST ANSWER

The RegEx

string.match(/\$((?:\d|\,)*\.?\d+)/g) || []

That || [] is for no matches: it gives an empty array rather than null.

Matches

  • $99
  • $.99
  • $9.99
  • $9,999
  • $9,999.99

Explanation

/         # Start RegEx
\$        # $ (dollar sign)
(         # Capturing group (this is what you’re looking for)
  (?:     # Non-capturing group (these numbers or commas aren’t the only thing you’re looking for)
    \d    # Number
    |     # OR
    \,    # , (comma)
  )*      # Repeat any number of times, as many times as possible
\.?       # . (dot), repeated at most once, as many times as possible
\d+       # Number, repeated at least once, as many times as possible
)
/         # End RegEx
g         # Match all occurances (global)

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.

2
On

Use match with regex as follow:

string.match(/\$\d+(\.\d+)?/g)

Regex Explanation

  1. / : Delimiters of regex
  2. \$: Matches $ literal
  3. \d+: Matches one or more digits
  4. ()?: Matches zero or more of the preceding elements
  5. \.: Matches .
  6. g : Matches all the possible matching characters

Demo

This will check if there is a possible decimal digits following a '$'

0
On

A non-regex approach: split the string and filter the contents:

var arr = string.split(' ').filter(function(val) {return val.startsWith('$');});