通过javascript在句子中删除的选定重复单词

时间:2019-03-08 14:05:16

标签: javascript jquery duplicates

我想删除在javascript中重复的句子中以@开头的一些单词,该如何实现。
例如:

"This is @banker does banking in a @bank, this @banker is good."  

在这句话中,我想从中删除多余的单词“ @banker”。

  1. 如何使用javascript?
  2. 考虑应该删除的每个单词,都应以“ @”开头

1 个答案:

答案 0 :(得分:3)

这是一个可能的解决方案:

const text = 'This is @banker does banking in a @bank, this @banker is good.';
const splittedWords = text.split(' ');

let newSentence = [];

splittedWords.forEach(word => {
    if (word.startsWith('@')) {
        if (newSentence.indexOf(word) === -1) {
            newSentence.push(word);
        }
    } else {
        newSentence.push(word);
    }
});

console.log(newSentence.join(' '));

更新

const text = 'This is @2, this is @3, this is @2';
const splittedWords = text.split(' ');

let newSentence = [];

splittedWords.forEach(word => {
    if (word.startsWith('@')) {
        cleanedSentence = newSentence.map(word => word.replace(/,/g, ''));
        cleanedWord = word.replace(/,/g, '');
        if (cleanedSentence.indexOf(cleanedWord) === -1) {
            newSentence.push(word);
        }
    } else {
        newSentence.push(word);
    }
});

console.log(newSentence.join(' '));