[英]JavaScript: match a word in a text with a word in array and replace it
我需要更改此文本:
var text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot`;
使用這兩個數組:
var arrOld = ["coffee", "apple", "banana" , "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"];
得到這樣的結果:
`this is an example text. 1laptop , 2 laptop , 1 keyboard, 2keyboard , ?mouse ,printer`
我正在嘗試類似的東西:
for (let i = 0; i < arrOld.length; i++) {
arrNew[i];
arrOld[i];
text.replace(arrOld[i],arrNew[i])
}
但它沒有用。
從 .replace 上的文檔( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace ):
“ replace()
方法返回一個新字符串,其中模式的部分或全部匹配被替換替換。”
這意味着text.replace()
不會操縱 text 變量。 要解決此問題,只需在循環中執行以下操作:
text = text.replace()
這會將更改的文本捕獲到文本變量中。 如果不這樣做,您正在進行更改,但您沒有使用它們(您忘記了它們)。
你可以使用String.prototype. replaceAll()
String.prototype. replaceAll()
:
var text = "this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot"; var arrOld = ["coffee", "apple", "banana", "carrot"]; var arrnew = ["laptop", "keyboard", "mouse", "printer"] for (let i = 0; i < arrOld.length; i++) { text = text.replaceAll(arrOld[i], arrnew[i]); } console.log(text);
也許還有Array.prototype. map()
Array.prototype. map()
:
var text = "this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot"; var arrOld = ["coffee", "apple", "banana", "carrot"]; var arrnew = ["laptop", "keyboard", "mouse", "printer"]; arrOld.map((old, i) => text = text.replaceAll(old, arrnew[i])); console.log(text);
replace 返回一個新string
而不是更改舊字符串
你可以使用reduce
還添加正則RegExp
,因為replace
僅適用於它找到的第一個匹配項
const text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana, another banana ,carrot`; var arrOld = ["coffee", "apple", "banana" , "carrot"]; var arrnew = ["laptop", "keyboard", "mouse", "printer"]; const resultWitoutRegexp = arrOld.reduce((res, textToChange, i) => res.replace(textToChange, arrnew[i]) , text) const result = arrOld.reduce((res, textToChange, i) => res.replace(new RegExp(textToChange, 'g'), arrnew[i]) , text) console.log(resultWitoutRegexp) console.log(result)
你可以試試這個。 從您的代碼修改。
const oldArray = ["coffee", "apple", "banana" , "carrot"]; const newArray = ["laptop", "keyboard", "mouse", "printer"]; let text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot`; const { length } = oldArray for (let i = 0; i < length; i++) { text = text.replace(oldArray[i], newArray[i]); } console.log(text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.