JavaScript String replace() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.replace() returns a new string with matches of a pattern swapped for a replacement (same API as MDN String.prototype.replace()). Learn string vs regex patterns, the g flag, capture groups, replacer functions, five examples, and try-it labs.

01

Kind

Instance method

02

Returns

New string

03

String pattern

First match only

04

Regex + g

All matches

05

Mutates?

No

06

Baseline

Widely available

Introduction

Need to swap one word for another, clean up a pattern, or rewrite part of a string with logic? replace() builds a new string from the old one by substituting matches.

Pass a string as the pattern and only the first match is replaced. Pass a RegExp with the g flag to replace every match. The second argument can be a plain string (with special $ patterns) or a function.

💡
Beginner tip

Want every occurrence of a plain string? Prefer replaceAll(), or use a regex with the g flag. Plain replace("a", "b") stops after the first "a".

This page is part of JavaScript String Methods. Related topics include match() and repeat().

Understanding the replace() Method

str.replace(pattern, replacement) searches str for pattern and returns a new string with matches rewritten.

  • A string pattern replaces only the first occurrence.
  • A RegExp without g also replaces only the first match.
  • A RegExp with g replaces every match.
  • replacement may be a string or a function.
  • The original string is never modified.

📝 Syntax

General form of String.prototype.replace:

JavaScript
str.replace(pattern, replacement)

Parameters

  • pattern — a string, or a RegExp (any object with Symbol.replace). Non-regex values are coerced to strings.
  • replacement — a string (may include $&, $1, …) or a function called for each match.

Return value

A string with matches replaced:

SituationResult
String patternFirst match only
Regex without gFirst match only
Regex with gEvery match
No matchSame text (new string)
Empty string patternReplacement prepended at the start

Useful replacement patterns (string replacement)

PatternInserts
$$A literal $
$&The whole matched text
$1, $2, …Capturing group 1, 2, … (regex only)

Common patterns

JavaScript
"cat cat".replace("cat", "dog");     // "dog cat"
"cat cat".replace(/cat/g, "dog");    // "dog dog"

"Xmas".replace(/xmas/i, "Christmas"); // "Christmas"

"Maria Cruz".replace(/(\w+)\s(\w+)/, "$2, $1");
// "Cruz, Maria"

⚡ Quick Reference

GoalCode
Replace first literalstr.replace("old", "new")
Replace all (regex)str.replace(/old/g, "new")
Case-insensitivestr.replace(/old/gi, "new")
Swap with groupsstr.replace(/(\w+) (\w+)/, "$2 $1")
Custom logicstr.replace(/pat/g, (m) => …)

🔍 At a Glance

Four facts to remember about String.replace().

Returns
string

New text with swaps

String pattern
first only

Not every match

All matches
/pat/g

Or use replaceAll

Mutates
no

Strings stay immutable

📋 replace() vs replaceAll() vs match()

replace()replaceAll()match()
PurposeSwap matches for new textSwap every matchFind matches
String patternFirst onlyAll matchesTreated as literal search
ReturnsNew stringNew stringArray or null
Best forFirst swap / regex powerClear “replace all”Reading matches

Examples Gallery

Examples follow MDN String.replace() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Replace one match, then use regex flags.

Example 1 — Basic String and Word Replace

MDN demo: replace a literal, then a word-boundary regex.

JavaScript
const paragraph = "This dog's name is just Dog! Yes, that is the name.";

paragraph.replace("name", "nickname");
// "This dog's nickname is just Dog! Yes, that is the name."

paragraph.replace(/\bis\b/, "was");
// "This dog's name was just Dog! Yes, that is the name."

paragraph.replace(/\bis\b/g, "was");
// "This dog's name was just Dog! Yes, that was the name."
Try It Yourself

How It Works

The literal "name" swaps only the first occurrence. Without g, the regex also stops after the first is. With g, both word-boundary matches become was.

Example 2 — Ignore Case with a Regex

MDN demo: the i flag matches regardless of capitalization.

JavaScript
const str = "Twas the night before Xmas...";
const newStr = str.replace(/xmas/i, "Christmas");

newStr;
// "Twas the night before Christmas..."
Try It Yourself

How It Works

/xmas/i matches "Xmas" even though the letters differ in case. Without i, that search would fail.

📈 Practical Patterns

Global replace, capture groups, and replacer functions.

Example 3 — Global + Ignore Case

MDN demo: replace every apples (any case) with oranges.

JavaScript
const re = /apples/gi;
const str = "Apples are round, and apples are juicy.";
const newStr = str.replace(re, "oranges");

newStr;
// "oranges are round, and oranges are juicy."
Try It Yourself

How It Works

The g flag enables multiple replacements. The i flag matches both "Apples" and "apples".

Example 4 — Capture Groups ($1 / $2)

MDN demo: switch first and last name with capturing groups.

JavaScript
const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
const newStr = str.replace(re, "$2, $1");

newStr;
// "Cruz, Maria"
Try It Yourself

How It Works

Group 1 is the first word; group 2 is the second. "$2, $1" puts last name first, then a comma, then the first name.

Example 5 — Replacer Function

MDN-style camelCase to kebab-case using a function.

JavaScript
function styleHyphenFormat(propertyName) {
  return propertyName.replace(/[A-Z]/g, function (match, offset) {
    return (offset > 0 ? "-" : "") + match.toLowerCase();
  });
}

styleHyphenFormat("borderTop");
// "border-top"

styleHyphenFormat("backgroundColor");
// "background-color"
Try It Yourself

How It Works

Each capital letter match is lowercased. If it is not at index 0, a hyphen is inserted before it. Functions are required when you need to transform the match before inserting it.

🚀 Common Use Cases

  • Fix one typo / token — swap the first occurrence of a word.
  • Global cleanup — regex with g (or replaceAll) for every match.
  • Case-insensitive edits — add the i flag.
  • Reorder parts — capture groups with $1 / $2.
  • Dynamic transforms — pass a function for per-match logic.
  • Not for reading matches — use match() / matchAll() when you only need the hits.

🧠 How replace() Builds the Result

1

Read pattern + replacement

Accept a string/RegExp pattern and a string or function replacement.

Input
2

Find matches

Search once, or repeatedly when the regex has the g flag.

Search
3

Build replacement text

Expand $ patterns, or call the replacer function for each match.

Swap
4

Return a new string

The original str is unchanged.

📝 Notes

  • A string pattern replaces only the first match.
  • Only a regex with the g flag replaces multiple times via replace().
  • Special $ patterns work in string replacements, not in values returned from a function.
  • Empty string pattern prepends the replacement: "xxx".replace("", "_")"_xxx".
  • Prefer replaceAll() when you clearly want every literal occurrence.
  • Always capture the return value — the original string does not update in place.

Browser & Runtime Support

String.prototype.replace() is Baseline Widely available — supported across modern browsers since July 2015 (and far earlier as a core language feature).

Baseline · Widely available

String.replace()

Safe for production in browsers and runtimes (Node.js, Deno, Bun). Use a g-flag regex or replaceAll() when you need every match.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
replace() Excellent

Bottom line: Use String.replace() to swap matches for new text. Remember: string patterns replace once; use /g or replaceAll() for every occurrence.

Conclusion

String.prototype.replace() is the standard way to rewrite parts of a string — from a single literal swap to global regex transforms and custom replacer functions. Choose the pattern carefully, and reach for replaceAll() when “every occurrence” is the goal.

Continue with match(), repeat(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use a string pattern for a simple first-only swap
  • Add the g flag (or use replaceAll) for every match
  • Use capture groups / $n to reorder parts
  • Use a function when the replacement must be computed
  • Assign the return value to a new variable

❌ Don’t

  • Expect replace("a", "b") to change every "a"
  • Forget that strings are immutable
  • Rely on $1 with a string pattern (groups need a RegExp)
  • Call .toLowerCase() on "$&" before replace — use a function instead
  • Use replace when you only need to inspect matches

Key Takeaways

Knowledge Unlocked

Five things to remember about String.replace()

Swap matches for new text without mutating the original.

5
Core concepts
🔎 02

String pattern

first only

Rule
🎯 03

All matches

/g or replaceAll

Tip
04

Groups

$1 $2 …

Regex
📄 05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.replace(pattern, replacement) returns a new string where matches of pattern are swapped for replacement. A plain string pattern replaces only the first match. A RegExp with the g flag can replace every match.
No. Strings are immutable. replace() returns a new string; the original stays the same.
Use a regular expression with the g (global) flag, or use String.prototype.replaceAll() for a clearer all-matches API.
Yes. Pass a function as the second argument. It runs for each match and its return value becomes the replacement text. Special $ patterns do not apply to that return value.
When pattern is a RegExp with capturing groups, $1 inserts the first group, $2 the second, and so on. $$ inserts a literal dollar sign. $& inserts the whole match.
An empty string pattern inserts the replacement at the start of the string. For example "xxx".replace("", "_") returns "_xxx".
Did you know?

replaceAll() arrived much later (ES2021) because developers kept forgetting the g flag on replace(). Both APIs remain useful — replace for first-match and advanced regex, replaceAll for clear “change every copy” intent.

More String Methods

Return to the hub for slice, trim, padStart, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful