JavaScript Tutorial

How To Replace All Instances of a String in JavaScript

Guide covering how to replace all occurrences of a string in JavaScript using replace, replaceAll, regex /g, RegExp constructor, split/join, and escaping special characters.

Drake Nguyen

Founder · System Architect

3 min read
How To Replace All Instances of a String in JavaScript
How To Replace All Instances of a String in JavaScript

Introduction

Replacing text inside strings is a routine task in JavaScript. This guide explains several ways to replace all occurrences of a string in JavaScript, from built-in methods like String.prototype.replace and String.prototype.replaceAll to regular-expression approaches and non-regex workarounds.

Note: choose the technique that matches your browser support and whether you need case-insensitive or special-character-aware replacement.

Prerequisites

  • Basic familiarity with JavaScript syntax and functions.
  • Understanding of regular expressions is helpful for the examples that use the /g (global) and /i (case-insensitive) flags.

Replace a single occurrence

String.prototype.replace by default changes only the first match when given a string pattern. This behavior can surprise developers expecting a global replacement.

const text = 'one fish two fish fish red fish';
const first = text.replace('fish', 'shark');
console.log(first); // 'one shark two fish fish red fish'

As shown above, only the first fish was replaced.

Replace all occurrences with a regular expression

The easiest and most common approach to replace multiple occurrences is to use a regular expression with the global flag /g. This is the standard javascript regex replace technique for broad text changes.

const text = 'one fish two fish fish red fish';
const replaced = text.replace(/fish/g, 'shark');
console.log(replaced); // 'one shark two shark shark red shark'

You can also combine the case-insensitive flag /i when needed: /pattern/gi supports global, case-insensitive replacements (javascript replace all case insensitive).

const mixed = 'Fish fish FISH';
const allInsensitive = mixed.replace(/fish/gi, 'shark');
console.log(allInsensitive); // 'shark shark shark'

Use the RegExp constructor

If your search pattern is stored in a variable, build a RegExp dynamically using the constructor and pass flags as a string. This is helpful when you need to set g or i at runtime.

const term = 'fish';
const re = new RegExp(term, 'gi');
const result = 'Fish fish FISH'.replace(re, 'shark');
console.log(result); // 'shark shark shark'

Replace all without regex

If you want to replace all occurrences of a plain substring without using regex, use split and join. This is a simple javascript replace all occurrences without regex trick that avoids regular-expression pitfalls such as special-character escaping.

const text = 'a+b+a+b';
const safe = text.split('+').join('-');
console.log(safe); // 'a-b-a-b'

The split/join method is reliable for fixed substrings and is often easier when you need to avoid escaping regex metacharacters.

Using String.prototype.replaceAll

Modern JavaScript provides replaceAll for direct global replacements of a substring. It treats the first argument as a plain string (not a regex) unless you pass a RegExp.

const s = 'spam spam spam';
const out = s.replaceAll('spam', 'eggs');
console.log(out); // 'eggs eggs eggs'

Note: replaceAll is not available in very old environments—use a polyfill or split/join fallback if you need wide compatibility.

Handling special characters and escaping

When you build a regex from user input or literals that include characters like . * + ? ^ $ ( ) [ ] { } | \ / -, escape them first; otherwise the regex will treat them as metacharacters. Here is a small helper to escape regex characters before constructing a RegExp:

function escapeRegex(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

const raw = 'this\-is\-my\-url';
const escaped = escapeRegex('\\-'); // escapes backslash and dash for safe regex
const cleaned = raw.replace(new RegExp(escaped, 'g'), '-');
console.log(cleaned); // 'this-is-my-url'

Common tasks such as replace special characters in javascript string or replacing hyphens/backslashes are handled by escaping before building a global RegExp.

Examples and best practices

  • For plain substring replacement and modern environments, prefer replaceAll for clarity (javascript replaceall example).
  • When you need flags like case-insensitive or want pattern matching, use replace with a regex and the /g flag (replace all occurrences using regex /g in javascript).
  • Escape user input when creating a RegExp (escape special characters in regex javascript replace).
  • Use split/join as a safe fallback to avoid regex complexity (javascript replace all occurrences without regex).

Conclusion

To replace all occurrences of a string in JavaScript you can choose between regex-based replacements (/g or RegExp constructor), the convenience of replaceAll, or a split/join approach without regex. Consider browser support, whether you need case-insensitive matching, and whether your pattern contains special characters when selecting the right method.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.