JavaScript replaceAll: A Practical Guide

Learn how to use JavaScript's replaceAll to replace every occurrence in strings. Explore syntax, edge cases, polyfills, and practical examples for clean, readable code.

JavaScripting
JavaScripting Team
·5 min read
replaceAll in Action - JavaScripting
Quick AnswerDefinition

In JavaScript, replaceAll is a string method that replaces every occurrence of a search value with a replacement value. Introduced in ES2021, it handles plain strings and, for RegExp searches with the global flag, can apply regex replacements. If you pass a non-global RegExp, replaceAll will throw. This makes wide replacements concise and readable.

Understanding the javascript replaceall API

In the realm of javascript replaceall, developers gain a safe, readable way to replace all instances of a string in one call. This section demonstrates the core behavior and contrasts it with older patterns. We start with a straightforward example and then extend to RegExp-based replacements that use the global flag. The keyword to watch here is javascript replaceall, which keeps discussions focused on a modern, standard approach.

JavaScript
const s = 'foo foo foo'; const t = s.replaceAll('foo', 'bar'); console.log(t); // bar bar bar
JavaScript
// RegExp with global flag is also supported const s2 = 'abc-123-ABC-123'; const t2 = s2.replaceAll(/123/g, '999'); console.log(t2); // abc-999-ABC-999

Why use replaceAll? It avoids the pitfalls of manual split/join hacks and makes intent explicit. When using a RegExp, the global flag is required; otherwise a TypeError is thrown. This section lays the groundwork for safe, expressive string transformations.

Edge cases and safe usage

We cover common edge cases to help you write robust code with javascript replaceall. First, consider how replaceAll behaves when the search value is an empty string. Inserting a replacement between every character is a deliberate consequence, so plan accordingly. Second, if the search term does not occur in the string, the original string remains unchanged. Finally, replacing with a RegExp that lacks the global flag will throw a TypeError, so you must supply /pattern/g when using a regex search.

JavaScript
const s = 'abc'; const t = s.replaceAll('', '-'); console.log(t); // -a-b-c
JavaScript
const s2 = 'hello world'; console.log(s2.replaceAll('x', 'y')); // hello world
JavaScript
try { 'foo'.replaceAll(/foo/, 'bar'); } catch (e) { console.log(e instanceof TypeError); // true }

Variations and guidance

  • Use string search values for simple text swaps for maximum readability.
  • If you must perform dynamic regex replacements, ensure the global flag is present.

Polyfills and older environments

If you need to support environments that lack String.prototype.replaceAll, you can provide a safe polyfill based on split/join. This preserves the intent of a global replacement while remaining compatible with older runtimes. The polyfill must be loaded before any code that calls replaceAll.

JavaScript
if (!String.prototype.replaceAll) { String.prototype.replaceAll = function(search, replacement) { // Coerce to string in case of non-string inputs const s = String(this); return s.split(search).join(replacement); }; } // Usage after polyfill: console.log('a-b-c'.replaceAll('-', '0'));

Notes

  • The polyfill uses split and join, which may have different performance characteristics on very large strings.
  • For complex regex-based needs, polyfills won’t help because your input requires a RegExp with global flag, which replaceAll handles directly when available.

Practical use cases in real-world data

Real-world code often benefits from replaceAll for template processing, normalization, and input cleanup. This section shows practical use cases with real data scenarios. The first example demonstrates simple placeholder replacement in a template. The second demonstrates case-insensitive replacement with a RegExp.

JavaScript
const template = 'Hello {{name}}, welcome to {{site}}!'; const result = template .replaceAll('{{name}}', 'Ada') .replaceAll('{{site}}', 'JavaScripting'); console.log(result); // Hello Ada, welcome to JavaScripting!
JavaScript
const s = 'Foo bar FOO BAR'; const t = s.replaceAll(/foo/gi, 'baz'); console.log(t); // baz bar baz BAR

Chaining and composition

  • You can chain multiple replaceAll calls to perform complex transformations in a readable sequence.
  • When dynamic input is involved, validate or sanitize inputs before applying regex-based replacements to avoid runaway ReDoS risk.

Alternatives: split/join vs replaceAll

Before replaceAll existed, developers often used split and join to achieve global replacement. This section compares both approaches to highlight readability, safety, and intent. We’ll show a side-by-side using a simple delimiter replacement and then discuss when replaceAll is preferred.

JavaScript
const s = 'a-b-c'; const withSplitJoin = s.split('-').join('0'); console.log(withSplitJoin); // a0b0c
JavaScript
const withReplaceAll = s.replaceAll('-', '0'); console.log(withReplaceAll); // a0b0c

When to choose replaceAll

  • For readability and intent, replaceAll clearly communicates a global replacement.
  • If you need complex logic around replacements or environments lacking replaceAll, split/join can be a viable fallback, though it’s usually less expressive.

Performance and testing strategies

Performance considerations matter when processing large strings or executing many replacements in hot paths. In most typical web app scenarios, replaceAll performs well enough for user-visible strings. To verify performance in your environment, perform micro-benchmarks and measure allocations. The example below uses console.time to compare replaceAll with a loop-based approach and highlights when the overhead matters.

JavaScript
const input = 'x'.repeat(10000) + 'end'; console.time('replaceAll'); input.replaceAll('x', 'y'); console.timeEnd('replaceAll');
JavaScript
let acc = input; console.time('loop'); for (let i = 0; i < 10000; i++) { acc = acc.split('x').join('y'); } console.timeEnd('loop');

Takeaway

  • In most apps, prefer replaceAll for clarity; optimize only after profiling shows a bottleneck.

Common pitfalls and best practices

Even with its simplicity, replaceAll can trip you up if you’re not mindful of inputs and environments. This section calls out common mistakes and best practices to keep your code robust and maintainable. Remember to validate user input when constructing dynamic regex patterns and avoid using an untrusted pattern without proper escaping.

JavaScript
// Best practice: validate inputs when building dynamic patterns let value = 'name'; let safePattern = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); let result = 'Hello name'.replaceAll(new RegExp(safePattern, 'g'), 'John'); console.log(result); // Hello John
JavaScript
// Pitfall: empty search string can create long results const s = 'abc'; const r = s.replaceAll('', '-'); console.log(r); // -a-b-c

Best practices

  • Prefer string literals for simple replacements to keep intent obvious.
  • Use RegExp with the g flag only when you truly need pattern-based replacements; otherwise a plain string yields clearer code.

Steps

Estimated time: 60-90 minutes

  1. 1

    Define test inputs

    Create a simple string and a replacement value. Verify the expected output using console.log to gain intuition about replaceAll behavior.

    Tip: Start with small, predictable inputs to see exact results.
  2. 2

    Try a basic string replacement

    Use replaceAll('old','new') to replace all occurrences in a sample string. Observe the difference from manual methods.

    Tip: Prefer plain strings first for readability.
  3. 3

    Experiment with RegExp

    Replace with a RegExp that has the global flag. Confirm behavior and edge cases like case sensitivity.

    Tip: Remember that RegExp without g will throw in replaceAll.
  4. 4

    Add a polyfill for legacy environments

    Provide a safe fallback to maintain compatibility with older runtimes that lack replaceAll.

    Tip: Polyfills should be loaded before dependent code.
  5. 5

    Integrate into a real workflow

    In a small project, replace template placeholders or normalize user input using replaceAll in a controlled, tested module.

    Tip: Write unit tests for common replacements to prevent regressions.
Pro Tip: Prefer replaceAll for clear intent; avoid convoluted split/join hacks when possible.
Warning: Avoid using untrusted dynamic RegEx without proper escaping; it can lead to TypeError or worse performance issues.
Note: If searchValue is an empty string, replacement inserts between every character.

Prerequisites

Required

Optional

Keyboard Shortcuts

ActionShortcut
CopyCopy code or selections in editors and terminalsCtrl+C
PasteInsert previously copied contentCtrl+V
FindSearch within the current documentCtrl+F
Toggle line commentComment/uncomment selected lines in editorsCtrl+/
Format documentApply consistent formatting in editors+Alt+F

Questions & Answers

What does String.prototype.replaceAll do?

replaceAll replaces every occurrence of a search value in a string with a replacement value. It supports string searches and RegExp with the global flag when available.

replaceAll replaces all occurrences of a search term in a string, using either a plain string or a global RegExp.

Can I use replaceAll in all browsers?

In modern environments (including Node.js 18+ and most current browsers), replaceAll is supported. For older runtimes, use a polyfill or a split/join fallback.

Yes in modern environments; for older setups, use a polyfill or manual methods.

What happens if I pass a RegExp without the global flag?

replaceAll will throw a TypeError if you pass a RegExp without the global flag. Ensure you use /pattern/g when needed.

If you use a RegExp, include the global flag, otherwise you’ll get an error.

How do I polyfill replaceAll?

You can polyfill by adding a split/join fallback on String.prototype.replaceAll that returns the replacement for every occurrence.

You can polyfill replaceAll using a split and join approach to simulate global replacement.

What about case-insensitive replacements with replaceAll?

Use a RegExp with the i flag (e.g., /pattern/gi) to perform case-insensitive replacements when needed.

Use a global, case-insensitive regexp if you need to match text regardless of case.

Is replaceAll faster than split/join?

In many cases replaceAll is faster and easier to read, but performance depends on string size and engine optimizations. Profile in your environment.

Often faster and clearer, but test in your specific environment.

What to Remember

  • Replace all occurrences with a single, readable call
  • Use strings by default; RegExp with g is allowed for patterns
  • Polyfills provide legacy support for older runtimes
  • Prefer replaceAll over split/join for clarity and maintainability

Related Articles