JavaScript string replace(); In this tutorial, we would love to show you, how you can replace the string in javaScript.
JavaScript String replace() Method
- Defination of Replace() Method
- Syntax
- Parameter of Replace() Method
- List of JavaScript String replace() Method Examples
- Example 1 – Replace Sub-String
- Example 2 – Global Search Modifier
- Example 3 – Without using Global Search
- Example 4 – Replace() Method is Case-Sensitive
- Example 5 – Replace() Method is Case-Sensitive Ignore
Defination of Replace() Method
The JavaScript string replace() method is used to replace a part of a given string with a new sub-string. This method searches for specified regular expression in a given string and then replace it if the match occurs.
Here you will learn how to use a global search modifier with replace() method. It will replace all the match elements otherwise the method replaces only the first match. JavaScript also provides an ignore flag to make the method case-insensitive.
Syntax
The replace() method is represented by the following syntax:
string.replace(orgStr,newStr);
Parameter of Replace() Method
orgStr– It represents the string to be searched and replaced.
newStr– It represents the new string that replaced with the searched string.
List of JavaScript String replace() Method Examples
Let’s take some examples of replace() method.
Example 1 – Replace Sub-String
Let’s take a simple example to replace a substring.
var str="hello world"; document.writeln(str.replace("world","world!"));
Output:
hello world!
Example 2 – Global Search Modifier
In this example, you will replace a regular expression using the global search modifier.
var str=" Learn PHP on tutsmake.com."; document.writeln(str.replace(/PHP/g,"javaScript"));
Output:
Learn javaScript on tutsmake.com.
Example 3 – Without using Global Search
In this example, you will replace a regular expression without using a global search.
var str=" Learn Node.js on tutsmake.com. Node.js is a well-known JavaScript framework."; document.writeln(str.replace(/Node.js/,"AngularJS")); //It will replace only first match.
Output:
Learn AngularJS on tutsmake.com. Node.js is a well-known JavaScript framework
Example 4 – Replace() Method is Case-Sensitive
In this example, you will see that the replace() method is case-sensitive.
var str=" Learn Node.js on tutsmake.com."; document.writeln(str.replace(/Node.JS/g,"AngularJS"));
Output:
Learn Node.js on tutsmake.com.
Example 5 – Replace() Method is Case-Sensitive Ignore
You can ignore the case-sensitive behavior of replace() method by using the ignore flag modifier. Let’s understand with the help of an example:
var str=" Learn Node.js on tutsmake.com."; document.writeln(str.replace(/Node.JS/gi,"AngularJS"));
Output:
Learn AngularJS on tutsmake.com.
Conclusion
In this tutorial, you have learned how to replace the string in javaScript using the replace() method.