DEV Community

Youn
Youn

Posted on

JavaScript String replace() Function: Replacing Text in a String

😄 This post is based on the content from coding.courses.

Definition and Usage

The replace() function for strings searches for a specific part of a string and replaces it with another string.

Features

  • Uses a specific substring or a regular expression pattern to search within the original string,
  • The matched portion is replaced with the desired string and returned.
  • By default, only the first match is replaced, but if you use a g flag in the regular expression pattern, all matches can be replaced.
  • The original string remains unchanged.

Basic Example

const str = "I like yellow the most~";
const replacedStr = str.replace("yellow", "blue");

console.log(replacedStr); // "I like blue the most~"
Enter fullscreen mode Exit fullscreen mode

Syntax

str.replace(searchValue, newValue);
Enter fullscreen mode Exit fullscreen mode

str is the string to which the replace() function is applied.

Parameters

# searchValue

Specifies what to search for in the string to be replaced.
You can provide either a specific substring or a regular expression pattern.

# newValue

Specifies the new string to replace the matched value.
You can provide either a string or a function that returns the replacement string.

  • If you provide a string, it replaces the first occurrence of searchValue.
  • If you provide a function, the function returns the replacement string for each match.

Return Value

Returns a new string where the searchValue has been replaced with newValue.
The original string is not modified.

#searchValue : How to Specify the Value to Replace

You can provide either a specific substring or a regular expression pattern to search for the target text.

- Searching with a Specific Substring

When searching with a specific substring, only the first match found is replaced.

const originalString = "Hello, JavaScript! JavaScript!";
const newString = originalString.replace("JavaScript", "JS");

// The matched portion is replaced with the desired string.
// Only the first occurrence is replaced.
console.log(newString); // Output: "Hello, JS! JavaScript!"

// The original string is not modified.
console.log(originalString); // Output: "Hello, JavaScript! JavaScript!"
Enter fullscreen mode Exit fullscreen mode

- Searching with a Regular Expression Pattern

const originalString = "I am 20 years old.";
const newString = originalString.replace(/\d+/, "**");
// \d+ matches one or more digits

// The matched portion is replaced with the desired string.
console.log(newString); // Output: "I am ** years old."

// The original string is not modified.
console.log(originalString); // Output: "I am 20 years old."
Enter fullscreen mode Exit fullscreen mode

Regular expression patterns also replace only the first match by default. However, if you use a pattern with the g flag, all matches can be replaced.

const text = "apple banana apple";

// Using the g flag
const result = text.replace(/apple/g, "orange");
console.log(result);  // Output: "orange banana orange"

// Without the g flag
const resultNotG = text.replace(/apple/, "orange");
console.log(resultNotG);  // Output: "orange banana apple"
Enter fullscreen mode Exit fullscreen mode

In the code above, using the /apple/g regular expression with the g flag replaces all occurrences of "apple" with "orange" in the string.

# newValue : How to Specify the Replacement

You can provide either a string or a function that returns the replacement when searchValue is matched.

- Providing a String

If you provide a string, the matched portion is replaced with the specified string.

const originalString = "Hello, JavaScript!";
const newString = originalString.replace("JavaScript", "JS");

console.log(newString); // Output: "Hello, JS!"
Enter fullscreen mode Exit fullscreen mode

- Providing a Function

If you provide a function, it is called for each match, and its return value is used as the replacement string.

const originalString = "Hello, JavaScript!";
const newString = originalString.replace("JavaScript", function(match) {
    // match is the entire substring found by replace()
    return match.toUpperCase();
});

console.log(newString); // Output: "Hello, JAVASCRIPT!"
Enter fullscreen mode Exit fullscreen mode

Here, match represents the entire substring found by replace(), and toUpperCase() is used to convert it to uppercase before returning.

- Providing a Function

function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
    return replacement;
}
Enter fullscreen mode Exit fullscreen mode

Each parameter has the following meaning:

  • match: The entire matched substring.
  • p1, p2, ..., pN: The substrings corresponding to each capturing group in the regular expression.
  • offset: The index of the match within the original string.
  • string: The original string.
  • groups: An object containing named capturing groups (only exists if the regular expression contains named groups, e.g., /(a)(?c)/).

The function should return the replacement value, which replace() uses. Using a function as newValue allows you to implement dynamic replacement logic for matched substrings.

Practical Examples

# Masking Part of an Email Address

const email = "john.doe@example.com";
const hiddenEmail = email.replace(/(?<=.{3})[^@](?=[^@]*@)/g, "*");

console.log(hiddenEmail);
// Output: "joh*************@example.com"

In this example, all characters except for the first three in the email address are replaced with asterisks ().
The regular expression (?<=.{3}) matches the position after the first three characters, and (?=[^@]
@) matches the position before the @ symbol.

# Removing HTML Tags

const htmlString = "<p>Hello, <strong>world</strong>!</p>";
const plainText = htmlString.replace(/<[^>]*>/g, "");

console.log(plainText);
// Output: "Hello, world!"

This example removes all HTML tags from a string, leaving only the plain text. The regular expression <[^>]*> matches any sequence that starts with < and ends with >, and replaces it with an empty string.

# Replacing Words

const sentence = "JavaScript is fun!";
const replacedSentence = sentence.replace("JavaScript", "TypeScript");

console.log(replacedSentence);
// Output: "TypeScript is fun!"

This example performs a simple word replacement. Using the replace() function, "JavaScript" is replaced with "TypeScript," resulting in the new sentence "TypeScript is fun!". Such straightforward replacements are commonly used in everyday string manipulation tasks.

References

JavaScript String replace() Function: Replacing Text in a String – codingCourses

The replace() function for strings returns a new string where one or more occurrences of a specific substring or a regular expression pattern are replaced by a specified replacement.

favicon coding.courses

Top comments (0)