gpt4 book ai didi

javascript - 替换字符串中与单独数组中的单词匹配的单词

转载 作者:行者123 更新时间:2023-12-01 00:03:13 24 4
gpt4 key购买 nike

我试图在字符串中与数组中的一组“过滤”单词匹配的任何单词前面添加 #。

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

关于我哪里出错了有什么想法吗?

最佳答案

Repl Example

您可以使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com