While working with Javascript, We often need to replace a character with other characters and remove space from a string. For this task string functions are available, Regular expression can also be used to achieve the same task.
var str = "Hello Ram, Hello Shyam Good Morning";
str.replace('Hello','Hi'); // output: Hi Ram, Hello Shyam Good Morning
Replace() function only replaces first match if we first argument as a string
var str = "Hello Ram, Hello Shyam Good Morning";
str.replace(new RegExp('Hello'), 'hi'); // output: Hi Ram, Hello Shyam Good Morning
A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text to replace operations.
Sometimes we need to replace all occurrences of a string with the one. The same can be done with below ways.
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red"); // ouput: Mr Blue has a red house and a red car
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/gi, "red"); // output: Mr red has a red house and a red car
Thank you!