Search code examples
javascriptregexcurrency

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


var string = 'Our Prices are $355.00 and $550, down form $999.00';

How can I get those 3 prices into an array?


Solution

  • 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.