How to use javascript replace() method

In Javascript, there is a handy function replace() for String Object. We can easily replace the sub-string with new string and also regular expression in available. Replace may be case-sensitive or case insensitive. Also global replacement can be obtained using this function.
Syntax

string.replace(regex/substring,replacetext)

replace() function takes two parameters.

  • regex/substring : Regular expression or a substring.
  • replacetext : What the word will be replaced with. This needs to be a string.

Example

var mystr="Hello user !"; 
mystr.replace("user",'Sachin');

Its output is:

Hello Sachin !

To perform case insensitive search we use ‘/i’ in the regex
For example

var mystr="Hello user !"; 
mystr.replace(/user/i,'Sachin');
var mystr="Hello User !"; 
mystr.replace(/user/i,'Sachin');

In both case output would be same.
Now for global replace ‘/g’ is used.

var mystr="Hello user ! Thanks for logging in user."; 
mystr.replace(/user/g,'Sachin');

Its output is:

Hello Sachin ! Thanks for logging in Sachin.

To obtain global, case insensitive search we need to use ‘g’ and ‘i’ together.

var mystr="Hello user ! Thanks for logging in User."; 
mystr.replace(/user/gi,'Sachin');

Its output is:

Hello Sachin ! Thanks for logging in Sachin.

Leave a Reply

Your email address will not be published. Required fields are marked *