The replace()
method replaces a specified value with another value in a string:
Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "Mytat");
var n = str.replace("Microsoft", "Mytat");
The replace()
method does not change the string it is called on. It returns a new string.
By default, the replace()
method replaces only the first match:
Example
str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "Mytat");
var n = str.replace("Microsoft", "Mytat");
By default, the replace()
method is case sensitive. Writing MICROSOFT (with upper-case) will not work:
Example
str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "Mytat");
var n = str.replace("MICROSOFT", "Mytat");
To replace case insensitive, use a regular expression with an /i
flag (insensitive):
Example
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "Mytat");
var n = str.replace(/MICROSOFT/i, "Mytat");
Note that regular expressions are written without quotes.
To replace all matches, use a regular expression with a /g
flag (global match):
Example
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "Mytat");
var n = str.replace(/Microsoft/g, "Mytat");
Practice Excercise Practice now