javascript

Replace characters globally Javascript

In JavaScript, the replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

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

Output

Color is blue and blue is a cold color

Live Demo

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.


Replace characters globally in Javascript

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

Live Demo

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

Live Demo


Replace characters globally - Case sensitive

Was this helpful?