jon*_*iat 11 javascript regex jquery replace
我希望能够在给定页面上找到与正则表达式匹配的价格文本,对其执行函数,然后替换输出.
例:
<div>The total is $12</div>
Run Code Online (Sandbox Code Playgroud)
变为: <div>The total is $24</div>
首先,你的正则表达式是有缺陷的.它可以修复和简化为:
/\$([\d,]+(?:\.\d+)?)/g
Run Code Online (Sandbox Code Playgroud)
它的设计使得第一个捕获组将是没有美元符号的数字本身.它找到一个可选的美元符号,后跟至少一个数字,后跟一个可选的句点,如果有一个句点,则后跟更多的数字.
然后,您可以在替换功能中使用它.为了使数字加倍,你必须传递一个函数作为执行加倍的第二个参数.这看起来像这样:
pageText.replace(/\$([\d,]+(?:\.\d+)?)/g,
function (string, c1) {
//If there are commas, get rid of them and record they were there
var comma = c1.indexOf(',') != -1;
c1 = c1.replace(/,/g, '');
//Parse and double
var value = '' + (parseFloat(c1) * 2);
//Reinsert commas if they were there before
if (comma) {
var split = value.split(".");
value = split[0].replace(/(\d)(?=(\d{3})+$)/g, "$1,");
if(split.length > 1)
value += "."+split[1];
}
//Return with dollar sign prepended
return '$' + value;
});
Run Code Online (Sandbox Code Playgroud)
c1是第一个捕获组,它只是没有美元符号的数字.它被解析为一个浮点然后加倍.如果原始字符串中有美元符号,则会在该数字前面放置一个美元符号.如果有逗号,则必须将其删除并在数字加倍后重新添加.毕竟,这一切都归还了.
这是一个jsfiddle的例子,所以你可以看到它的实际效果:http://jsfiddle.net/dB8bK/49/