我想将文本块中的数字替换为减半的值,但是仅如果数字后跟某些单词(与使用正则表达式增加字符串中的数字不同,后者没有这样的条件并且每个字符串仅替换一个匹配项)。例如:
14个苹果和18个香蕉花了6美元。
到
7个苹果和9个香蕉花了6美元。
这里仅将水果名称后面的数字减半。我不认为这可以通过简单的 replace
实现,而且我不知道如何使用
replace
回调来做到这一点。Set
中时才将数字除以二。
let str = '14 apples and 18 bananas cost 6 dollars.';
const allowedFruits = new Set(['apples', 'bananas']);
let res = str.replace(/\d+ \w+/g, m => {
const [num, word] = m.split(' ');
if(allowedFruits.has(word)) return num/2 + ' ' + word;
return m;
});
console.log(res);