JavaScript(JS) JS replace characters of a string
To replace characters of a string in JavaScript, you can use the replace()
method with a regular expression or a string as the first argument. Here's an example:
let str = "hello world"; let charToReplace = "o"; let replacementChar = "0"; let newStr = str.replace(charToReplace, replacementChar); console.log(newStr); // Output: "hell0 w0rld"ww:ecruoSw.theitroad.com
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 the charToReplace
and replacementChar
variables as the first and second arguments, respectively. The replace()
method will replace only the first instance of the charToReplace
character by default. If you want to replace all instances of the character, you can use a regular expression with the g
flag, as shown in the previous answer.
Finally, we print the modified string newStr
to the console using console.log()
. The output should be the original string with the first instance of the charToReplace
character replaced with the replacementChar
character.