使用Javascript中的字符串中的$获取所有价格

问题描述 投票:-1回答:3
var string = 'Our Prices are $355.00 and $550, down form $999.00';

我怎样才能将这3个价格变成阵列?

javascript regex currency
3个回答
3
投票

RegEx

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

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

火柴

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

说明

/         # 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)

为了更容易地匹配像.99这样的数字我使第二个数字成为必需(\d+),同时使第一个数字(以及逗号)可选(\d*)。这意味着,从技术上讲,像$999这样的字符串与第二个数字(在可选的小数点之后)匹配,这与结果无关 - 这只是一个技术性问题。


3
投票

非正则表达式方法:拆分字符串并过滤内容:

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

2
投票

使用matchregex如下:

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

正则表达式解释

  1. /regex的分隔符
  2. \$:匹配$字面
  3. \d+:匹配一个或多个数字
  4. ()?:匹配前面元素中的零个或多个
  5. \.:匹配.
  6. g:匹配所有可能匹配的字符

Demo

这将检查'$'后面是否有可能的十进制数字

© www.soinside.com 2019 - 2024. All rights reserved.