Search code examples
javascriptregexmultiplication

Multiply numbers on regex matched lines


I would like to multiply all the numbers in the lines containing "buyPrice:" with a certain value.

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

I discovered a piece of code (see below) that returns "buyPrice: NaN" instead of "buyPrice: 1000" etc if I for example use a multiplier of 2. I would appreciate the help!

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>


Solution

  • In the code you provided, the whole matched text is parsed as a number while you only need to convert the digit sequence into a number. Thus, enclose the digit matching part with parentheses and pass the second argument to the anonymous method:

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

    Here, (\d+) will capture 1+ digits into Group 1 and this value will be available through the group1 argument.