1

I have a var contains string and I have array with words from the string called oldWords and new array with the new words called newWords I want to replace oldWords with newWords in the string I already try to do it with for loop but it return the string with only the last word replaced.

Code:

let myStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sapien magna.",
    old_Words = ["Lorem", "ipsum"],
    new_Words = ["word1", "word2"];
    
for (let i = 0; i < old_Words.length; i++) {
  var newStr = myStr.replace(old_Words[i], new_Words[i]);
}

console.log(newStr);

output should be:

"word1 word2 dolor sit amet, consectetur adipiscing elit. Fusce sapien magna."
0

2 Answers 2

3

Start with let newStr = myStr; before the loop, then do newStr = newStr.replace(...) inside the loop:

let myStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sapien magna.",
    old_Words = ["Lorem","ipsum"],
    new_Words = ["word1","word2"],
    newStr = myStr;

for (let i = 0; i < old_Words.length; i++){
  newStr = newStr.replace(old_Words[i], new_Words[i]);
}
console.log(newStr);

Sign up to request clarification or add additional context in comments.

2 Comments

Note: put Lorem again in your myStr.. It won't replace.
@Keith yes I want to replace it for the first time only>
2

You can replace all the occurrences of old words with new words as follows:

NOTE: This can replace multiple occurrences of words as well.

let myStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor Fusce sapien magna.",
    old_Words = ["Lorem","ipsum"],
    new_Words = ["word1","word2"];
    
old_Words.forEach((oldWord, idx) => {
  myStr = myStr.replace(RegExp(oldWord, 'g'), new_Words[idx])
});

console.log(myStr)

let myStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem Fusce ipsum sapien magna.",
    old_Words = ["Lorem","ipsum"],
    new_Words = ["word1","word2"];
    
old_Words.forEach((oldWord, idx) => {
  myStr = myStr.replace(RegExp(oldWord, 'g'), new_Words[idx])
});

console.log(myStr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.