搜索价格文本,执行功能,并替换为输出

时间:2014-03-03 04:25:33

标签: javascript jquery regex replace

我希望能够在给定页面上找到与正则表达式匹配的价格文本,对其执行函数,然后替换输出。

示例:

<div>The total is $12</div>
  1. RegEx与12美元的价格文本相匹配
  2. 取12并乘以2 = 24
  3. 将12替换为24
  4. 成为:<div>The total is $24</div>

    这是一个JSFiddle with my test code(请务必在上面提到我的问题,谢谢!)

    以下是regEx I am using

7 个答案:

答案 0 :(得分:8)

首先,你的正则表达式是有缺陷的。它可以修复和简化为:

/\$([\d,]+(?:\.\d+)?)/g

它的设计使得第一个捕获组将是没有美元符号的数字本身。它找到一个可选的美元符号,后跟至少一个数字,后跟一个可选的句点,如果有一个句点,则后跟更多的数字。

然后,您可以在替换功能中使用它。为了使数字加倍,你必须传递一个函数作为执行加倍的第二个参数。这看起来像这样:

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;
});

c1是第一个捕获组,它只是没有美元符号的数字。它被解析为一个浮点然后加倍。如果原始字符串中有美元符号,则会在该数字前面放置一个美元符号。如果有逗号,则必须将其删除并在数字加倍后重新添加。在所有这些之后,它全部归还。

以下是jsfiddle的示例,以便您可以看到它的实际效果:http://jsfiddle.net/dB8bK/49/

答案 1 :(得分:2)

试着看看这是不是你在寻找配偶。

基本上,我刚刚将您的replace功能更改为

document.body.innerHTML = pageText.replace(/12/g, 'IT WORKS!!!!!!!!!!!');

自从做了

document.body.innerHTML = pageText.replace('12', 'IT WORKS!!!!!!!!!!!');

只会取代第一次出现'12'。

Demo

答案 2 :(得分:2)

这个应该适合你:

document.body.innerHTML = pageText.replace(/\$\d+([.,]\d+)?(?=\D\D)/g, function (match) {
    // getting digits only
    digits = match.replace(/\D/g, "");
    num = "" + digits * 2;

    // handle input: $0.009
    if(digits.match(/^0+/)){
        // left padding
        num = Array(digits.length - String(num * 2).length+1).join('0') + num;
    }

    pos_dot = match.indexOf(".");
    if(pos_dot >= 0){
        pos_dot = match.length - pos_dot - 1;
        num = num.substring(0, num.length - pos_dot) + "." + num.substring(num.length - pos_dot, num.length);

    }

    pos_comma = match.indexOf(",");
    if(pos_comma >= 0){
        pos_comma = match.length - pos_comma - 1;
        num = num.substring(0, num.length - pos_comma) + "," + num.substring(num.length - pos_comma, num.length);
    }

    return "$"+num;
});

示例输入:

<li>$12</li>
<li>$14.99</li>
<li>$2</li>
<li>$dollars</li>
<li>14.99</li>
<li>$12,000</li>
<li>$12,00,0</li>
<li>$0,009</li>

示例输出:

$24
$29.98
$4
$dollars
14.99
$24,000
$12,00,0
$0,018

注意:如果您需要,可以通过更改(?=\D\D)部分来调整正则表达式。

答案 3 :(得分:1)

您无需使用regex。 在span内取价并在此范围内添加一个类。由于span是内联元素,因此不会损害html设计。

我认为这比regEx

更好

尝试这样:

HTML:

<div>The total is $<span class="price">12</span></div>

<div>The total is $<span class="price">100</span></div>

Jquery的:

 $('.price').each(function(i,e){
      $(this).text(parseFloat($(this).text()*2));
  });

fiddle

答案 4 :(得分:1)

function dollarChange(match, p0, p1, p2, offset, string) {
    // pN = Nth in-parentheses match

    // Remove commas (reinjected later)
    var hasComma = (p1.indexOf(',') > -1);
    if (hasComma) p1 = p1.replace(',', '');

    // Get decimal precision
    var precision = 0;
    if (p2) {
        p1 = p1 + p2;
        precision = p2.length - 1;
    }

    // Process number
    p1 = Number(p1);
    var value = p0 + (p1 * 2).toFixed(precision);

    // Inject commas if previously found
    if (hasComma) {
        var parts = value.toString().split('.');
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        value = parts.join('.');
    }

    return value;
}

// Execute replacement
document.body.innerHTML =
    document.body.innerHTML.replace(/([$])([\d,]+)(\.[\d]+)?/g,
                                    dollarChange);

<强> JSFiddle Demo

从理论上讲,$可以替换为其值前面的任何货币符号,其值使用.作为小数点分隔符。

请注意,此处使用的正则表达式仅匹配前面带有美元符号的数字(例如14.25将不匹配)

答案 5 :(得分:1)

(function(context){
  var pattern=/(\$)(\d([\d\,\.]+)?)/g,
      callback=function(_,dollar,price){
           price=price.replace(/,/g,''); 
           return dollar + parseFloat(price)*2;
      },
      html=context.innerHTML.replace(pattern,callback);
  context.innerHTML=html;
})(document.body);

如果您不关心价格重新格式化 ckeck the fiddle

答案 6 :(得分:1)

首先生成你的正则表达式。

var reg_exp = /\$[0-9]*\.?[0-9]*/g;  //This is your Custom Requested Regex 

生成与正则表达式匹配的字符串列表。

var matches = document.body.innerHTML.match(reg_exp)

假设您要在HTML的所有主体上搜索正则表达式。

定义转换函数

var transform = function(match){
    var result;
    /* Logic for genarting the resulting string, populate it in result */
    result = match.replace('$','');
    result = parseFloat(result);
    result = result * 2;
    result = '$' + result;
    return result;
};

将每个匹配转换为结果。

matches.forEach(function(match){
    console.log(match)
    result = transform(match);
    document.body.innerHTML.replace(match, result)
});

虽然已经有其他答案可以达到你想要的效果,但我的答案总结了你想要的方式来做到这一点