JavaScript(JS) JS replace all occurrences of a string
To replace all occurrences of a string in JavaScript, you can use the replace()
method with a regular expression. Here's an example:
let str = "hello hello world"; let stringToReplace = "hello"; let replacementString = "hi"; let newStr = str.replace(new RegExp(stringToReplace, "g"), replacementString); console.log(newStr); // Output: "hi hi world"
In this code, we define a string str
that contains some instances of the string we want to replace. We also define a stringToReplace
variable that contains the string we want to replace, and a replacementString
variable that contains the string we want to replace it with.
We use the replace()
method with a regular expression new RegExp(stringToReplace, "g")
to replace all instances of the stringToReplace
string with the replacementString
string. The g
flag in the regular expression tells replace()
to perform the replacement globally (i.e., on all matches).
Finally, we print the modified string newStr
to the console using console.log()
. The output should be the original string with all instances of the stringToReplace
string replaced with the replacementString
string.