JavaScript String replace() Method Explained: Basics, Regex, and Practical Examples

1. Introduction

JavaScript is one of the most widely used programming languages in web development. In particular, string manipulation is a frequently used feature when handling user input and data processing. Among these features, the replace() method is known as a powerful tool that allows you to easily perform string replacement operations.

In this article, we will thoroughly explain the JavaScript replace() method from the basics to advanced usage. In addition to fundamental examples, we will also cover advanced replacements using regular expressions and practical real-world use cases. This content is designed to be useful for beginners through intermediate developers.

2. Basics of the replace() Method

What Is the replace() Method?

The replace() method is a built-in JavaScript function used to replace specific parts of a string with another string. By using this method, you can efficiently edit and transform string data.

Syntax

string.replace(pattern, replacement)
  • pattern: The string or regular expression to search for.
  • replacement: The replacement string or a callback function.

Basic Usage

The following example demonstrates a simple string replacement.

let text = "Hello, world!";
let result = text.replace("world", "JavaScript");
console.log(result); // "Hello, JavaScript!"

In this code, the string “world” is replaced with “JavaScript”.

Important Notes

  1. replace() replaces only the first matched occurrence.
  2. To replace all matched occurrences, you must use a regular expression with the g flag.

3. Advanced Replacement Using Regular Expressions

What Are Regular Expressions?

Regular expressions are powerful tools for describing string patterns. In JavaScript, regular expressions allow you to easily perform complex pattern matching and replacement operations.

Replacement Examples Using Regular Expressions

let text = "apple, banana, apple";
let result = text.replace(/apple/g, "orange");
console.log(result); // "orange, banana, orange"

Types of Flags

  • g: Global replacement (replaces all matches)
  • i: Case-insensitive replacement
  • m: Multiline mode

Advanced Example: Case-Insensitive Replacement

let text = "Hello, hello, HELLO";
let result = text.replace(/hello/gi, "hi");
console.log(result); // "hi, hi, hi"

4. Replacing Multiple Occurrences

Replacing All Matches

To replace all matching occurrences in a string, use the g flag in a regular expression.

let text = "cat dog cat bird";
let result = text.replace(/cat/g, "fish");
console.log(result); // "fish dog fish bird"

Technique for Replacing Multiple Different Strings at Once

let text = "red blue green";
let replacements = {red: "pink", blue: "cyan", green: "lime"};

Object.keys(replacements).forEach(key => {
  let regex = new RegExp(key, "g");
  text = text.replace(regex, replacements[key]);
});

console.log(text); // "pink cyan lime"

This approach allows you to replace multiple patterns at once while improving code readability.

5. Dynamic Replacement Using Callback Functions

What Is a Callback Function?

A callback function is invoked during the replacement process and allows you to customize the operation using the current match information.

Examples of Dynamic Replacement

1. Reordering Strings

let text = "Tanaka, Taro";
let result = text.replace(/(\w+), (\w+)/, (match, p1, p2) => {
  return `${p2} ${p1}`;
});
console.log(result); // "Taro Tanaka"

2. Converting Date Formats

let date = "2024-12-25";
let formattedDate = date.replace(/(\d{4})-(\d{2})-(\d{2})/, (match, year, month, day) => {
  return `${month}/${day}/${year}`;
});
console.log(formattedDate); // "12/25/2024"

6. Handling Special Characters and Escape Sequences

What Are Special Characters?

In regular expressions, certain characters have special meanings as metacharacters. To use these characters literally in search or replacement operations, you must use escape sequences.

Replacing Strings That Contain Special Characters

Example 1: Replacing a String That Contains a Period

let text = "www.example.com";
let result = text.replace(/\./g, "-");
console.log(result); // "www-example-com"

Example 2: Removing a Dollar Sign

let price = "$1,000";
let result = price.replace(/\$/g, "");
console.log(result); // "1,000"

Replacing HTML Escape Characters

Example: Escaping HTML Tags

let html = "<div>Hello!</div>";
let result = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
console.log(result);
// "&lt;div&gt;Hello!&lt;/div&gt;"

7. Practical Use Cases and Advanced Techniques

Converting Line Breaks to <br> Tags

let text = "Hello\nWorld\nJavaScript";
let result = text.replace(/\n/g, "<br>");
console.log(result);
// "Hello<br>World<br>JavaScript"

Manipulating URL Parameters

let url = "https://example.com/?id=123&lang=en";
let result = url.replace(/lang=en/, "lang=ja");
console.log(result);
// "https://example.com/?id=123&lang=ja"

Sanitizing User Input

function sanitizeInput(input) {
  return input.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

let userInput = "<script>alert('XSS');</script>";
let safeInput = sanitizeInput(userInput);
console.log(safeInput);
// "&lt;script&gt;alert('XSS');&lt;/script&gt;"

8. Important Notes and Best Practices

Be Aware That Only the First Match Is Replaced

let text = "apple apple orange";
let result = text.replace("apple", "banana");
console.log(result); // "banana apple orange"

Pay Attention to Case Sensitivity

let text = "JavaScript is powerful. javascript is versatile.";
let result = text.replace(/javascript/gi, "JS");
console.log(result);
// "JS is powerful. JS is versatile."

Do Not Forget to Escape Special Characters

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

let text = "Price: $100";
let result = text.replace(new RegExp(escapeRegExp("$"), "g"), "USD ");
console.log(result);
// "Price: USD 100"

9. Conclusion

Article Summary

  • Basic Usage: Explained the syntax and simple examples of the replace() method.
  • Regular Expression Applications: Covered how to use regular expressions and flags for advanced replacement operations.
  • Callback Functions: Demonstrated dynamic replacement techniques with practical examples.
  • Practical Examples: Introduced useful techniques such as URL manipulation and input sanitization.
  • Best Practices: Explained important caveats and performance-related considerations.

Final Thoughts

The JavaScript replace() method is a versatile and powerful tool that can be used effectively from basic to advanced scenarios. We will continue to provide useful JavaScript-related content, so stay tuned.

広告