Javatpoint Logo
Javatpoint Logo

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.

Test it Now

Output:

JavaScript

Example 2

In this example, we will replace a regular expression using global search modifier.

Test it Now

Output:

Learn AngularJS on Javatpoint. AngularJS is a well-known JavaScript framework. 

Example 3

In this example, we will replace a regular expression without using global search.

Test it Now

Output:

Learn AngularJS on Javatpoint. Node.js is a well-known JavaScript framework

Example 4

In this example, we will see that replace() method is case-sensitive.

Test it Now

Output:

Learn Node.js on Javatpoint. 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:

Test it Now

Output:

Learn AngularJS on Javatpoint. AngularJS is a well-known JavaScript framework.

Next TopicJavaScript String




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA