How does the replace() Method Work in JavaScript?

JavaScript replace() inline method 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(param1, param2)

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 this example, we are replacing just a string in the text.

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.


Related Posts