【问题标题】:Conditionally replace with calculation有条件地替换为计算
【发布时间】:2021-08-07 16:19:36
【问题描述】:

我想用减半的值替换文本块中的数字,但如果数字后跟某些单词。例如:

14 个苹果和 18 个香蕉要 6 美元。

7 个苹果和 9 个香蕉要 6 美元。

这里仅将数字后跟水果名称的数字减半。我不认为这可以通过简单的replace 来实现,我不知道如何通过replace 回调来实现。

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    您可以匹配所有数字后跟一个单词,并且仅当该单词位于特定的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);

    【讨论】:

    • @Frungi 很高兴为您提供帮助。
    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2012-01-03
    • 2016-11-17
    相关资源
    最近更新 更多