With the new replaceAll string method, you can replace all occurrences of a string within a string.
Syntax:
string.replaceAll(search, replaceWith)
The replaceAll
method replaces all appearances of the search string with replaceWith
within the string it is attached to.
Example:
let sentence = “I am alive. But, even if as I am alive, I feel I am not”
let newSentence = sentence.replaceAll(“am”, “was”);
console.log(newSentence)
// “I was alive. But, even if as I was alive, I feel I was not"
At the time of writing this, replaceAll
is currently supported by all modern browsers, according to caniuse. So, you should have no problem using it.
However, if you need to support older browsers or the IE browser, then you can try this hacky method using the string.split() and array.join() methods.
First, use the split method to divide the original string into substrings at every point where the string to be replaced occurs:
let sentence = “I am alive. But, even if as I am alive, I feel I am not”
let splitSentence = sentence.split(‘am’)
console.log(splitSentence)
//output: ["I ", " alive. But, even if as I ", " alive, I feel I ", " not"]
The split method puts the substrings into an array and returns the array.
Next, use the join method to join all the substrings together while putting the string to be replaced with, in between:
Let finalSentence = splitSentence.join('was')
console.log(finalSentence)
//output: "I was alive. But, even if as I was alive, I feel I was not"
Blog Credits: Linda Ikechukwu
Comments are closed.