首页 > 解决方案 > 通过javascript删除句子中的选定重复词

问题描述

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

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

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

  1. 我怎样才能在javascript中做到这一点?
  2. 考虑应该删除的每个单词都以“@”开头

标签: javascriptjqueryduplicates

解决方案


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

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(' '));


推荐阅读