我想删除在javascript中重复的句子中以@开头的一些单词,该如何实现。
例如:
"This is @banker does banking in a @bank, this @banker is good."
在这句话中,我想从中删除多余的单词“ @banker”。
答案 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(' '));