[英]JavaScript: match a word in a text with a word in array and replace it
[英]Replace words in string that match word in a separate array
我正在尝试在字符串中与数组中的一组“过滤器”单词匹配的任何单词前添加一个 #。
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
关于我哪里出错的任何想法?
forEach
回调的第二个参数是index ,您当前正在迭代,而不是值。 您还应该对句子中的单词调用toLowerCase
以与wordsArray
中的wordsArray
单词进行wordsArray
:
let wordsArray = ['she', 'smile']; let sentence = 'She has a big smile'; let sentenceArray = sentence.split(" "); wordsArray.forEach((vals) => { sentenceArray.forEach((sVal, j) => { if (sVal.toLowerCase() === vals) { sentenceArray[j] = `#${sVal}`; } }) }); console.log(sentenceArray)
但是,与嵌套循环相比,构造一组wordsArray
计算复杂wordsArray
会更低( O(n)
而不是O(n ^ 2)
),而且更加优雅:
const wordsArray = ['she', 'smile']; const wordsSet = new Set(wordsArray); const sentence = 'She has a big smile'; const result = sentence.split(" ") .map(word => wordsSet.has(word.toLowerCase()) ? '#' + word : word); console.log(result);
您可以使用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
})
wordsArray.forEach((word) =>sentence = sentence.replace(new RegExp(word,"ig"),"#"+word))
迭代过滤器中的所有单词,然后使用正则表达式替换句子中的单词 new RegExp(word, "ig") 第一个参数是要匹配的短语 第二个参数“ig”只是标志,“i”忽略大小写灵敏度,“g”在全球范围内搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.