在 JavaScript 中使用正则表达式从字符串中过滤出百分比

filter out a percentage from a string using a regular expression in javascript

本文关键字:字符串 过滤 百分比 正则表达式 JavaScript      更新时间:2023-09-26

我有以下字符串值:£-155 (-2.2%)

从中,我希望能够提取任何数字并且可能包含/可能不包含"-"减号的内容。 所以以上将是:-2.2

我还需要知道该值是否具有上述形式的百分比......条件语句将在最终代码中使用。

思潮?

为什么要使用正则表达式来处理这么简单的事情?为什么不直接抓住字符串中的最后一个字符并检查它是数字还是%。

同样,如果要删除它,只需使用 .substr() 方法从字符串中删除最后一个字符:

http://www.w3schools.com/jsref/jsref_substr.asp

你基本上想要一个与数字匹配的正则表达式,这在之前已经回答了很多次。

然后,一旦有了它,只需添加一个可选的百分号(%? )并检查它在匹配字符串中是否存在。

// An optional sign and either an integer followed by an optional fraction
// or a decimal fraction.
var numberRe = '[+-]?(?:[0-9]+(?:[.][0-9]*)?|[.][0-9]+)';
// Matches a number (in group 1)
// and an optional percentage in parentheses (in group 2).
var quantity = new RegExp(
    '(' + numberRe + ')(?:''s*[(]''s*(' + numberRe + ')''s*%''s*[)])?'); 

如果与quantity匹配,则应获得组 1 中的数字和组 2 中的任何百分比。

JSON.stringify(quantity.exec('£-155 (-2.2%)'))
["-155 (-2.2%)", "-155", "-2.2"]

要将它们作为数字获取,请使用 parseFloat 或一元+

var match = quantity.exec('£-155 (-2.2%)');
var n = +match[1], pct = match[2] != null ? +match[2] / 100 : NaN;
alert('n = ' + n + ', whole = ' + (pct ? n / pct : "unknown"));