JavaScript(JS) JS replace all instances of a character in a string
To replace all instances of a character in a string in JavaScript, you can use the replace()
method with a regular expression. Here's an example:
let str = "hello world"; let charToReplace = "o"; let replacementChar = "0"; let newStr = str.replace(new RegExp(charToReplace, "g"), replacementChar); console.log(newStr); // Output: "hell0 w0rld"
In this code, we define a string str
that contains some characters. We also define a charToReplace
variable that contains the character we want to replace, and a replacementChar
variable that contains the character we want to replace it with.
We use the replace()
method with a regular expression new RegExp(charToReplace, "g")
to replace all instances of the charToReplace
character with the replacementChar
character. 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 charToReplace
character replaced with the replacementChar
character.