Mastering JavaScript replace(): Complete Guide with Regex, Callbacks, and Best Practices

1. Introduction

JavaScript is one of the most widely used programming languages in web development. In particular, string manipulation is a common task when handling user input or processing data. Among these, the replace() method is known as a powerful tool that makes string replacement simple and efficient. In this article, we will explain the JavaScript replace() method in detail, from basics to advanced techniques. We will cover not only the basic usage but also advanced replacements using regular expressions and practical examples, making it useful for both beginners and 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. With this method, you can efficiently edit or transform string data.

Syntax

string.replace(pattern, replacement)
  • pattern: The string or regular expression to search for.
  • replacement: The string to replace with, 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.”

Notes

  1. replace() only replaces the first match.
  2. If you want to replace all matches, you need to use a regular expression with the g flag.

3. Advanced Replacement with Regular Expressions

What is a Regular Expression?

Regular expressions are powerful tools used to represent string patterns. In JavaScript, you can use regex to easily perform complex searches and replacements.

Example: Replacement with 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 (replace all matches)
  • i: Case-insensitive replacement
  • m: Multiline mode

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, use the g flag in your regex.
let text = "cat dog cat bird";
let result = text.replace(/cat/g, "fish");
console.log(result); // "fish dog fish bird"

Technique: Replace 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, improving code readability.

5. Dynamic Replacement with Callback Functions

What is a Callback Function?

A callback function is invoked during the replacement process and can use match information to customize the result.

Examples of Dynamic Replacement

1. Swapping String Order

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

2. Converting Date Format

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 are considered metacharacters with special meanings. To use them literally in searches or replacements, you need to escape them with escape sequences.

Replacing Strings Containing Special Characters

Example 1: Replacing a String Containing a Period

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

Example 2: Removing 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 Examples and Advanced Techniques

Converting Line Breaks into <br> Tags

let text = "HellonWorldnJavaScript";
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. Notes and Best Practices

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."

Avoid Missing Escapes for 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 Recap

  • Basic Usage: Explained the syntax and simple replacement examples of the replace() method.
  • Regex Applications: Learned how to use regular expressions and flags for advanced replacements.
  • Callback Functions: Covered how to perform dynamic replacements with practical examples.
  • Practical Examples: Introduced techniques useful in real-world applications such as URL manipulation and sanitization.
  • Best Practices: Explained notes and performance considerations in detail.

Final Thoughts

The JavaScript replace() method is a versatile tool that can be applied from basic to advanced scenarios. We will continue to provide helpful information about JavaScript, so stay tuned!
広告