JavaScript String replace() Method
The JavaScript string replace() method is used to replace a part of a given string with a new substring. This method searches for specified regular expression in a given string and then replace it if the match occurs.
We can use global search modifier with replace() method to replace all the match elements otherwise the method replace only first match. JavaScript also provides ignore flag to make the method case-insensitive.
Syntax
The replace() method is represented by the following syntax:
Parameter
originalstr – It represents the string to be searched and replaced.
Newstr – It represents the new string that replaced with the searched string.
Return
It returns the new string with the specified replacement.
JavaScript String replace() Method Example
Let’s see some examples of replace() method.
Example 1
Let’s see a simple example to replace a substring.
Output:
JavaScript
Example 2
In this example, we will replace a regular expression using global search modifier.
Output:
Learn AngularJS on TutorAspire . AngularJS is a well-known JavaScript framework.
Example 3
In this example, we will replace a regular expression without using global search.
Output:
Learn AngularJS on TutorAspire . Node.js is a well-known JavaScript framework
Example 4
In this example, we will see that replace() method is case-sensitive.
Output:
Learn Node.js on TutorAspire . Node.js is a well-known JavaScript framework.
Example 5
We can ignore case-sensitive behaviour of replace() method by using ignore flag modifier. Let’s understand with the help of example:
Output:
Learn AngularJS on TutorAspire . AngularJS is a well-known JavaScript framework.