javascript - 通过javascript删除句子中的选定重复词
问题描述
我想删除句子中以@开头的一些单词,这些单词在javascript中重复,我该如何实现它。
例如:
"This is @banker does banking in a @bank, this @banker is good."
在这句话中,我想从中删除多余的单词“@banker”。
- 我怎样才能在javascript中做到这一点?
- 考虑应该删除的每个单词都以“@”开头
解决方案
这是一个可能的解决方案:
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(' '));
推荐阅读
- android - 如何获取 Oreo 中正在运行的应用程序列表?
- django - 如何保护在 django 中创建的目录,以便只有 django 应用程序可以访问它
- google-cloud-datalab - Google Cloud Datalab 未运行单元格:文件夹创建和保存以及检查点失败
- wso2 - 在 wso2 api 管理器中进行身份验证后的重定向
- php - Prestashop 1.6 - 从 TPL 按钮调用函数
- javascript - 从处理子域但不处理ajax请求的子域传递php会话
- electron - 64位windows电子js的命令代码是什么?
- ios - 停用 TLS 1.0 TLS 1.1 对 iOS 应用程序的影响
- android - 奥利奥及以上的广播接收器
- azure - 在 Drupal 站点中进行 Azure AD 身份验证的过程是什么?