简体   繁体   中英

Replace words in string that match word in a separate array

I am trying to add a # in front of any words in a string that match a set of 'filter' words in an 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)
        }
    })
});

This is what it is spitting out in the console.

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

Any ideas on where I am going wrong?

The second parameter of the forEach callback is the index , you're currently iterating over, not the value. You should also call toLowerCase on the word in the sentence to compare against the lower-cased word in the 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)

But rather than a nested loop, constructing a Set of the wordsArray would be less computationally complex ( O(n) instead of O(n ^ 2) ), in addition to being more elegant:

 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);

Repl Example

You can use Array.map to iterate through each word in the sentence, then if it matches return the word with a # symbol.

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”在全球范围内搜索。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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