根据出现的次数将一个单词替换为另一个单词

时间:2018-01-29 19:11:30

标签: javascript arrays dictionary join split

我有一句话:

Hello there how is it going? I am good, Is it hot? I get it. 

鉴于以下内容:[{"I", 2}, {"is": 1}],我想转换单词I的第二次出现,并将其替换为:<i>I</i>和第一次出现的单词is并用<i>is</i>替换它,所以现在我的最后一句是:

Hello there how <i>is</i> it going? I am good, Is it hot? <i>I</i> get it

键是我要替换的单词,值是我想要替换该单词的位置。

我的尝试:

let sentence = "Hello there how is it going? I am good, Is it hot? I get it";
let keyValuePair = [{"I", 2}, {"is": 1}];
keyValuePair.map(value => {
  for (let k in value) {
    sentence = sentence.split(k).join('<b>'+  k + '</b>');
  }
});

以上不考虑分词,而是字符和位置。

1 个答案:

答案 0 :(得分:0)

您可以迭代替换数组并计算出现次数并在必要时替换。

var string = 'Hello there how is it going? I am good, Is it hot? I get it.';

string =  [{ I: 2 }, { is: 1 }].reduce((s, o) => {
    var count = 0,
        key = Object.keys(o)[0],
        value = o[key];
        
    return s.replace(new RegExp('\\b' + key + '\\b', 'g'), s => ++count === value ? '<i>' + s + '</i>': s);
}, string);

console.log(string);