JavaScript String replace() Method
In this article, we will tell you how to replace string in javascript. sometimes we need to replace a string with a specified string.
Now, in the following example, we use the replace() method the replace a specified string. so you can see the below syntax.
Syntax
string.replace(searchValue, newValue);
The search value finds in a string, and newValue replaces the existing search value into a string.
Example
1 2 3 | var str = "Hello World"; var res = str.replace("World", "John"); console.log(res); //output Hello John |
javascript replace multiple occurrences
if you want to replace multiple occurrences in javascript. then you can easily replace using replace() functions. so you can see the following syntax and example for replace multiple occurrences.
Syntax
string.replace(searchValue, newValue).replace(searchValue, newValue)…;
Example
1 2 3 | var str = "Hello World"; var res = str.replace("Hello", "John").replace("World", "Doe"); console.log(res); //output John Doe |
javascript string replace using regex
If you want to replace multiple occurrences in javascript. then you can easily replace using replace() functions. so you can see the following syntax and example for replace multiple occurrences.
Syntax
string.replace(regexp/substr, newSubStr/function[, flags]);
Example
1 2 3 4 | var str = "Hello World"; var res = /World/gi; var newstr = str.replace(res, "John"); console.log(newstr); //output Hello John |