2016-11-04 121 views
0

我想將包含「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>

+0

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

+0

它工作!非常感謝!真的很感謝幫助。 – AvidLearner

+0

很高興爲你效勞。請考慮接受答案(請參閱[如何接受SO答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work))。 –

回答

0

在您所提供的代碼,整個匹配的文本解析爲一個號碼,而你只需要數字序列轉換成一個數字。因此,附上與括號中的數字匹配的部分,第二個參數傳遞給匿名方法:

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

這裏,(\d+)將捕獲1+位成第1組,該值將是可通過group1參數。