var str = "Color is Green and green is a cold color"; var result = str.replace(/green/gi, "blue"); console.log(result) // -> Color is blue and blue is a cold color
Color is blue and blue is a cold color
In this code example, the string "Color is Green and green is a cold color" is stored in the variable str. The replace() method is then used to replace all instances of the word "green" in the string with the word "blue". The result is then logged into the console.
If you want to replace all occurrences of a particular character in a string, you can use the replace() method. This method takes two arguments: the character to be replaced, and the character to replace it with.
For example, the following code replaces first occurrences of "a" with "b":
var my_string = "aabcdaab"; my_string = my_string.replace("a", "b"); console.log(my_string); // -> babcdaab
Replace all occurences if characters in a string
var my_str = "aabcdaab"; my_str = my_str.replace(/a/gi, "b"); console.log(my_str); // -> bbbcdbbb