在正则表达式匹配的行上乘以数字

时间:2016-11-04 18:09:19

标签: javascript regex multiplication

我想将包含“buyPrice:”的行中的所有数字乘以一定值。

shops:
blocks:
  name: "&9&lBlocks (page %page%)"
  items:
    1:
      type: item
      item:
        material: GRASS
        quantity: 64
      buyPrice: 500
      sellPrice: 50
      slot: 0
    2:
      type: item
      item:
        material: DIRT
        quantity: 64
      buyPrice: 500
      sellPrice: 30
      slot: 1
    3:
      type: item
      item:
        material: GRAVEL
        quantity: 64
      buyPrice: 500
      sellPrice: 50
      slot: 2

我发现一段代码(见下文)返回“buyPrice:NaN”而不是“buyPrice:1000”等,如果我使用2的乘数我会很感激帮助!

addEventListener('load', function() {
document.getElementById('replace').addEventListener('click', function() {
    window.factor = parseInt(prompt('Which factor should the values be multiplied with?', 1));
    if (factor) {
        var input = document.getElementById('textinput');
        input.value = input.value.replace(/sellPrice: [0-9]+/g, function(match) { return 'sellPrice: ' + (parseInt(match, 10) * window.factor); });
    }
});
});
<button id="replace">Multiply px values</button>
<textarea style="width:100%;height:2000px;" id="textinput"></textarea>

1 个答案:

答案 0 :(得分:0)

在您提供的代码中,整个匹配的文本被解析为数字,而您只需要将数字序列转换为数字。因此,用括号括起数字匹配部分,并将第二个参数传递给匿名方法:

input.value = input.value.replace(/buyPrice: (\d+)/g, function(match, group1) { 
    return 'buyPrice: ' + (parseInt(group1, 10) * window.factor); 
});

在这里,(\d+)会将1+个数字捕获到第1组中,此值将通过group1参数提供。

相关问题