I need to change this text:
var text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot`;
using these 2 arrays :
var arrOld = ["coffee", "apple", "banana" , "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"];
to get result like this:
`this is an example text. 1laptop , 2 laptop , 1 keyboard, 2keyboard , ?mouse ,printer`
I was trying something like:
for (let i = 0; i < arrOld.length; i++) {
arrNew[i];
arrOld[i];
text.replace(arrOld[i],arrNew[i])
}
but it didn't work.
From the docs on .replace ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace ):
"The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement."
This means that text.replace()
doesn't manipulate the text variable. To fix this, simply do the following in your loop:
text = text.replace()
This will catch the changed text into the text variable. Without doing this, you are making the changes, but you are not using them (you forget them).
You could use String.prototype.
: :
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);
And maybe also Array.prototype.
: :
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 returns a new string
instead of changing the old one
you can use reduce
also add RegExp
because replace
works only for the first match it found
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)
You can try this. Modified from your code.
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);
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.