How do I replace all occurrences of a string in JavaScript?

To replace all occurrences of a string in JavaScript, you can use either replaceAll() (modern method) or replace() with a regex (legacy-safe method). Below is a detailed explanation with examples:

1. Using replaceAll() (ES2021+)

Syntax:

string.replaceAll(searchValue, replaceValue);
  • searchValue: The substring or regex pattern to replace (must include /g flag if using regex).
  • replaceValue: The string to replace matches with.

Examples:

  1. Replace all occurrences of a string:
   const text = "apple banana apple";
   const result = text.replaceAll("apple", "orange");
   console.log(result); // "orange banana orange"
  1. Case-insensitive replacement (use a regex with /gi flags):
   const text = "Apple apple APPLE";
   const result = text.replaceAll(/apple/gi, "orange");
   console.log(result); // "orange orange orange"
  1. Replace special characters (e.g., dots in filenames):
   const filename = "image.version1.jpg";
   const updated = filename.replaceAll(".", "-");
   console.log(updated); // "image-version1-jpg"

Notes:

  • Browser Support: Works in modern browsers (Chrome 85+, Firefox 77+, Node.js 15+). Not supported in Internet Explorer.
  • Regex Requirement: If using a regex as searchValue, it must include the /g flag to avoid errors.

2. Using replace() with Regex (Legacy Support)

Syntax:

string.replace(regexPattern, replaceValue);
  • Use a regex with the /g (global) flag to replace all matches.
  • Escape regex special characters (e.g., ., *, $) if using dynamic search strings.

Examples:

  1. Basic global replacement:
   const text = "apple banana apple";
   const result = text.replace(/apple/g, "orange");
   console.log(result); // "orange banana orange"
  1. Case-insensitive replacement:
   const text = "Apple apple APPLE";
   const result = text.replace(/apple/gi, "orange");
   console.log(result); // "orange orange orange"
  1. Dynamic search strings (escape regex characters):
   function replaceAll(str, find, replace) {
     // Escape regex special characters (e.g., ".", "$", "?")
     const escapedFind = find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
     const regex = new RegExp(escapedFind, 'g');
     return str.replace(regex, replace);
   }

   // Example usage:
   const filename = "file.name.txt";
   const updated = replaceAll(filename, ".", "-");
   console.log(updated); // "file-name-txt"
  1. Replace with captured groups (advanced):
   const text = "2023-10-25";
   const result = text.replace(/(\d{4})-(\d{2})-(\d{2})/g, "$2/$3/$1");
   console.log(result); // "10/25/2023"

Key Differences

MethodUse CaseSpecial CharactersBrowser Support
replaceAll()Simple string replacements.Auto-handled as literals.Modern browsers (ES2021+).
replace() + RegexDynamic patterns or legacy environments.Require escaping.All browsers (including IE).

When to Use Which?

  • replaceAll(): Use for simple, direct replacements in modern environments.
  • replace() + Regex: Use for dynamic search terms, case insensitivity, or backward compatibility.

Common Pitfalls

  1. Forgetting the /g Flag:
   // Incorrect: Only replaces the first "apple"
   const result = text.replace("apple", "orange");
   // Correct: Use /g flag
   const result = text.replace(/apple/g, "orange");
  1. Unescaped Regex Characters:
   // Incorrect: "." is a regex wildcard
   text.replace(/./g, "-"); // Replaces EVERY character with "-"
   // Correct: Escape the "."
   text.replace(/\./g, "-");

By mastering these methods, you can handle all string replacement scenarios in JavaScript!

Leave a Reply

Your email address will not be published. Required fields are marked *