Try it yourself with our free Regex Tester tool — runs entirely in your browser, no signup needed.

How to Use regex to replace in JavaScript

How to use regex to replace in JavaScript

Regular expressions (regex) are a powerful tool for text manipulation in JavaScript. One of the most common use cases for regex is replacing text patterns in a string. In this guide, we'll explore how to use regex to replace in JavaScript, covering the basics, common edge cases, and performance tips.

Quick Example

Here's a minimal example that replaces all occurrences of a word in a string:

const text = "Hello world, world is beautiful";
const regex = /world/g;
const replacement = "earth";

const newText = text.replace(regex, replacement);
console.log(newText); // Output: "Hello earth, earth is beautiful"

This code uses the replace() method to replace all occurrences of the word "world" with "earth" in the original string.

Step-by-Step Breakdown

Let's break down the code line by line:

  • const text = "Hello world, world is beautiful";: We define the original string.
  • const regex = /world/g;: We define the regex pattern to match the word "world". The g flag at the end makes the replacement global, so all occurrences are replaced, not just the first one.
  • const replacement = "earth";: We define the replacement string.
  • const newText = text.replace(regex, replacement);: We use the replace() method to replace the matched pattern in the original string with the replacement string.
  • console.log(newText);: We log the resulting string to the console.

Handling Edge Cases

Empty/Null Input

When dealing with empty or null input, it's essential to handle these cases to avoid errors. Here's an example:

function replaceText(text, regex, replacement) {
  if (!text) return "";
  return text.replace(regex, replacement);
}

const text = "";
const regex = /world/g;
const replacement = "earth";

const newText = replaceText(text, regex, replacement);
console.log(newText); // Output: ""

In this example, we add a simple check to return an empty string if the input is empty or null.

Invalid Input

When dealing with invalid input, such as a non-string value, we should handle these cases to avoid errors. Here's an example:

function replaceText(text, regex, replacement) {
  if (typeof text !== "string") {
    throw new Error("Input must be a string");
  }
  return text.replace(regex, replacement);
}

const text = 123;
const regex = /world/g;
const replacement = "earth";

try {
  const newText = replaceText(text, regex, replacement);
  console.log(newText);
} catch (error) {
  console.error(error); // Output: "Input must be a string"
}

In this example, we add a check to ensure the input is a string, and throw an error if it's not.

Large Input

When dealing with large input strings, performance can become a concern. Here's an example:

const text = "Hello world, world is beautiful".repeat(1000);
const regex = /world/g;
const replacement = "earth";

const startTime = performance.now();
const newText = text.replace(regex, replacement);
const endTime = performance.now();
console.log(`Replacement took ${endTime - startTime}ms`);

In this example, we use the performance.now() method to measure the time it takes to perform the replacement.

Unicode/Special Characters

When dealing with Unicode or special characters, we should ensure our regex pattern is properly escaped. Here's an example:

const text = "Hello §world, § is beautiful";
const regex = /\§/g;
const replacement = "earth";

const newText = text.replace(regex, replacement);
console.log(newText); // Output: "Hello earthworld, earth is beautiful"

In this example, we use the \ character to escape the special character § in the regex pattern.

Common Mistakes

Mistake 1: Forgetting the g flag

Without the g flag, only the first occurrence of the pattern will be replaced.

const text = "Hello world, world is beautiful";
const regex = /world/; // WRONG: missing `g` flag
const replacement = "earth";

const newText = text.replace(regex, replacement);
console.log(newText); // Output: "Hello earth, world is beautiful"

Corrected code:

const regex = /world/g;

Mistake 2: Not handling edge cases

Failing to handle edge cases can lead to errors or unexpected behavior.

const text = null;
const regex = /world/g;
const replacement = "earth";

const newText = text.replace(regex, replacement); // ERROR: Cannot read property 'replace' of null

Corrected code:

function replaceText(text, regex, replacement) {
  if (!text) return "";
  return text.replace(regex, replacement);
}

Mistake 3: Using a regex pattern with a capture group

Using a regex pattern with a capture group can lead to unexpected behavior.

const text = "Hello world, world is beautiful";
const regex = /(world)/g; // WRONG: unnecessary capture group
const replacement = "earth";

const newText = text.replace(regex, replacement);
console.log(newText); // Output: "Hello earth, earth is beautiful" ( incorrect )

Corrected code:

const regex = /world/g;

Performance Tips

Tip 1: Use a regex pattern with a ^ anchor

Using a regex pattern with a ^ anchor can improve performance by reducing the number of false positives.

const text = "Hello world, world is beautiful";
const regex = /^world/g; // Improved performance
const replacement = "earth";

const newText = text.replace(regex, replacement);

Tip 2: Use a regex pattern with a \b word boundary

Using a regex pattern with a \b word boundary can improve performance by reducing the number of false positives.

const text = "Hello world, world is beautiful";
const regex = /\bworld\b/g; // Improved performance
const replacement = "earth";

const newText = text.replace(regex, replacement);

Tip 3: Use the RegExp.prototype.exec() method

Using the RegExp.prototype.exec() method can improve performance by avoiding the creation of an intermediate array.

const text = "Hello world, world is beautiful";
const regex = /world/g;

let match;
while ((match = regex.exec(text)) !== null) {
  console.log(match[0]); // Output: "world", "world"
}

FAQ

Q: What is the difference between replace() and replaceAll()?

A: replace() replaces only the first occurrence of the pattern, while replaceAll() replaces all occurrences.

Q: How do I replace a pattern with a dynamic value?

A: You can use a function as the replacement value, which will be called for each match.

Q: Can I use regex to replace text in a non-string value?

A: No, regex can only be used to replace text in a string value.

Q: How do I handle Unicode characters in my regex pattern?

A: You can use the \u escape sequence to represent Unicode characters in your regex pattern.

Q: Can I use regex to replace text in a large input string?

A: Yes, but be aware of performance considerations and use techniques like anchoring and word boundaries to improve performance.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp