![](/img/trans.png)
[英]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.