JavaScript String replace() Tutorial

In this section, we will learn what the replace() method is and how to use it in JavaScript.

JavaScript String replace() Method

Sometimes we have a string value and want to replace a sub-value in that string with a new one. In situations like this, we can use the `replace()` method.

JavaScript String replace() Syntax

string.replace(searchvalue, newvalue)

String replace() Method Parameters:

The `replace()` method takes two arguments:

  • The first argument is the sub-value that we’re looking for in the target string.

Note: this value can also be a regular expression.

  • The second argument is the new value that we want to replace it with the value that we’re searching for.

Note:

  • If the first argument is a string non-regular expression value, the method will only replace the first occurrence of this sub-value.
  • But if the first argument is a regular expression with the global modifier `g` set to on, then all the occurrences will be replaced with the value of the second argument.

String replace() Method Return Value:

The return value of this method is a new string, where the specified value is replaced with the new value.

Example: replace JavaScript string

const name = "John Doe John Doe John Doe John Doe";

const res = name.replace("John", "Omid");

console.log(res);

Output:

Omid Doe John Doe John Doe John Doe

As you can see, because the first argument is just a string (non-regular expression) value, only the first match was replaced with the new value, which is `Omid`.

Example: JavaScript replace regex

const name = "John Doe John Doe John Doe John Doe";

const res = name.replace(/John/g, "Omid");

console.log(res);

Output:

Omid Doe Omid Doe Omid Doe Omid Doe

JavaScript String Remove

Using the replace() method, we can remove a sub-string value from the target text-string as well.

For this to happen, we should set an empty space as the value of the second argument of the repalce() method.

Example: JavaScript String Remove

const name = "John Doe John Doe John Doe John Doe";

const res = name.replace(/John/g, "");

console.log(res);

Output:

' Doe Doe Doe Doe'
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies