How does the replace() Method Work in JavaScript?

Last updated on March 10, 2023

The JavaScript built-in method replace() searches the specified string and returns a new string after replacing it. It accepts two parameters, the first parameter can be a string value or a regular expression. The second parameter is a string value of a replacement or It can be a function that matches the value.

Syntax:

string.replace(searchString, newString)

Parameters:

  • param1: is the regular expression that is to be replaced or a string value
  • param2: is a string that will replace the content of the given string.

Example:

In the blow example, the word blue is replaced with green through the replace method.

let text = "The blue sweater itches. I will wear a red t-shirt and blue jeans.";
let result = text.replace("blue", "green");

// Output
: The green sweater itches. I will wear a red t-shirt and blue jeans.

Very simple use of replace() method In this example, replace() method accepts two parameters and both have the same type(string). parameter one (blue) is replaced with parameter two (green).

Regular Expression:

Sometimes we need to replace multiple words or a single word or special characters in the strings then we have to define a pattern. If the pattern matches with any word in the string it should be replaced with some words or empty space.

Syntax: string.replace(RegExp, replacement);

Example:

const originalString = "<div><p>Hey that's <span>something</span></p></div>";
const strippedString = originalString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
//Output : "Hey that's something"

In the above example string has a div and paragraph element. These elements needed to be replaced with empty space to handle this situation. We used a regular expression pattern in the replace method “/(<([^>]+)>)/gi” first parameter. In the result, we got output without any HTML characters.

Conclusion:

The JavaScript’s built-in method replace() is very helpful to replace any single word, letter or character, and also accept a regular expression which matches the pattern and replaces the specific word or special character, with some word or empty space.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts