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

标签 javascript arrays

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

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/

相关文章:

java - for 循环返回空并且单击时没有显示任何内容

c++ - C++中数组的大小是否灵活?

php - 拉拉维尔。 toArray() 转换后不能将 StdClass 类型的对象用作数组

javascript - jQuery 中的动态数组名称

javascript - 更改图标以在angularjs中展开折叠

javascript - 你如何获得#xxxxxx 颜色的色调?

java - 只想填充二维数组的顶行和底行

javascript - EXTJS4 X模板

javascript - Kendo Editor - 动态生成的 HTML 元素上的 Javascript 函数调用

ruby-on-rails - Ruby 查看 csv 数据