繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM