在 Javascript 中将字符串中带有 $ 的所有价格放入数组中

Nic*_*iwi -1 javascript regex currency

var string = 'Our Prices are $355.00 and $550, down form $999.00';
Run Code Online (Sandbox Code Playgroud)

如何将这 3 个价格放入数组中?

Seb*_*mon 5

正则表达式

\n\n
string.match(/\\$((?:\\d|\\,)*\\.?\\d+)/g) || []\n
Run Code Online (Sandbox Code Playgroud)\n\n

|| []是没有匹配的情况:它给出一个空数组而不是null.

\n\n

火柴

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

解释

\n\n
/         # Start RegEx\n\\$        # $ (dollar sign)\n(         # Capturing group (this is what you\xe2\x80\x99re looking for)\n  (?:     # Non-capturing group (these numbers or commas aren\xe2\x80\x99t the only thing you\xe2\x80\x99re looking for)\n    \\d    # Number\n    |     # OR\n    \\,    # , (comma)\n  )*      # Repeat any number of times, as many times as possible\n\\.?       # . (dot), repeated at most once, as many times as possible\n\\d+       # Number, repeated at least once, as many times as possible\n)\n/         # End RegEx\ng         # Match all occurances (global)\n
Run Code Online (Sandbox Code Playgroud)\n\n

为了.99更轻松地匹配数字,我将第二个数字设置为强制 ( \\d+),同时将第一个数字(连同逗号)设置为可选 ( \\d*)。这意味着,从技术上讲,像这样的字符串与第二个数字(可选小数点之后)$999匹配,这对于结果\xe2\x80\x99并不重要\xe2\x80\x8a\xe2\x80\x94\xe2\x80\ x8ait\xe2\x80\x99s 只是一个技术细节。

\n