JavaScript String replace() method

The JavaScript string replace() method eliminates a given string with the specified replacement. By default, it will replace the first match only. To replace all matches we have to use a global identifier.

Syntax:

string.replace(string1, string2) 

Parameters: string1: It represents the string to be searched and replaced. string2: It represents the new string that will replace the searched string.

Return: Modified String.

Example:

<!DOCTYPE html>
<html>
<body>
<script>
var str1 ="Best tutorial website: w3spoint";
var str2 ="Learn Spring on w3spoint. Spring is one of the most popular framework.";
//Replace websire with site.
document.write(str1.replace('website', 'site'));
document.write("</br>");
//Replace only first match.
document.writeln(str2.replace(/Spring/,'Spring MVC'));
document.write("</br>");
//Replace all matches
document.writeln(str2.replace(/Spring/g,'Spring MVC'));
document.write("</br>");
//Replace all matches with ignore case
document.writeln(str2.replace(/Spring/gi,'Spring MVC'));
</script>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com