我试图在字符串中与数组中的一组“过滤”单词匹配的任何单词前面添加 #。
This is what I have so far
let wordsArray = ['she', 'smile'];
let sentence = 'She has a big smile';
let sentenceArray = sentence.split(" ");
wordsArray.forEach((i, vals) => {
sentenceArray.forEach((j, sVal) => {
if (sVal === vals) {
sentenceArray[j] = `#${j}`;
console.log(sentenceArray)
}
})
});
这就是它在控制台中输出的内容。
app.js:17 (5) ["She", "has", "a", "big", "smile", She: "#She"]
app.js:17 (5) ["She", "has", "a", "big", "smile", She: "#She", has:
"#has"] app.js:23 She has a big smile
关于我哪里出错了有什么想法吗?
最佳答案
您可以使用Array.map
遍历句子中的每个单词,如果匹配则返回带有#
符号的单词。
let wordsArray = ['she', 'smile'];
let sentence = 'She has a big smile';
let sentenceArray = sentence.split(" ");
sentenceArray = sentenceArray.map((word) => {
let matchIndex = wordsArray.indexOf(word.toLowerCase())
return (matchIndex !== -1)
? '#'.concat(word)
: word
})
关于javascript - 替换字符串中与单独数组中的单词匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60573261/