Replacing occurrences of a pattern found in a string with a specified replacement string : replace()

Java Script @ Freshers.in

The replace() method executes a search for a match in a string based on a regular expression or a fixed string, and returns a new string where the matched patterns are replaced by a replacement string.

Syntax:

The basic syntax of the replace() method is as follows:

string.replace(pattern, replacement)
  • pattern: A RegExp object or a substring to be replaced. If it’s a substring, only the first occurrence will be replaced.
  • replacement: The string that replaces the substring specified by the pattern or a function to be invoked to create the new substring.

It’s important to note that the original string will remain unchanged.

Examples and Execution: The examples below demonstrate various uses of the replace() method. You can execute these examples in any JavaScript environment, such as browser developer tools, online sandboxes, or Node.js.

Basic Usage – Replacing a Fixed String:

let message = "Hello, World!";
let newMessage = message.replace("World", "Universe");
console.log(newMessage); // Outputs: "Hello, Universe!"
Using regular expressions – Global replacement:
let text = "Blue is new; blue is bold.";
let newText = text.replace(/blue/gi, "red");
console.log(newText); // Outputs: "Red is new; red is bold."

Here, /blue/gi is a regular expression that searches for the pattern “blue” globally (g flag for global) and is case-insensitive (i flag).

Replacement using a function:
let str = "The year is 2023.";
let newStr = str.replace(/\d+/g, (match) => parseInt(match) + 1);
console.log(newStr); // Outputs: "The year is 2024."

In this scenario, we’re using a function as the replacement. The function is automatically passed the matched portion, which we then manipulate and return.

Formatting User Input
function formatUsername(username) {
  return username.trim().replace(/\s+/g, "_").toLowerCase();
}

let rawInput = "  User Name ";
let formattedInput = formatUsername(rawInput);
console.log(formattedInput); // Outputs: "user_name"
formatUsername processes a raw username input, removing extra spaces and replacing spaces between words with underscores, making a clean, formatted username.
Author: user