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