JavaScript String Replace: Syntax, Examples, and Tips

How-to basics · Updated November 22, 2026

JavaScript’s String.prototype.replace() method searches a string and returns a new string with a match replaced; it does not change the original. Use a literal search value to replace its first occurrence, or a regular expression with the g flag to replace every match.

What the replace() method does

replace() is a method available on JavaScript strings. Its basic form is text.replace(searchValue, replacement). The first argument says what to find, and the second says what to put in its place. The result is another string, so you can save it, return it, or use it directly in an expression.

For example, if let message = 'Tea is ready';, then message.replace('Tea', 'Coffee') produces 'Coffee is ready'. The value of message remains 'Tea is ready'. This matters when writing code that assumes a string has been updated: assign the result if you want to keep it.

The method is useful for targeted edits, such as correcting a word, changing a delimiter, formatting a value, or transforming text that matches a pattern. It is not a general-purpose in-place editing operation. JavaScript strings are immutable, so methods such as replace() create results rather than modifying characters in the existing string.

Basic syntax and a first example

The method accepts a search value and a replacement value. The search value is commonly a string or a regular expression; the replacement can be a string or a function. A simple example is:

const label = 'Draft: Q3 report';
const finalLabel = label.replace('Draft:', 'Final:');

console.log(finalLabel); // Final: Q3 report
console.log(label);      // Draft: Q3 report

The search is case-sensitive when it is a plain string. Thus 'Report'.replace('report', 'summary') returns 'Report', unchanged. The capitalization must match, or you can use a regular expression with the case-insensitive i flag, as in 'Report'.replace(/report/i, 'summary').

If there is no match, replace() returns a string with the same contents as the original. It does not throw an error just because the requested text is absent. The value still is a new method result in the sense that the method returns a string; code should depend on its contents, not object identity.

Replacing the first match or every match

A frequent surprise is that passing a string as the first argument replaces only its first matching occurrence. For example, 'red, red, red'.replace('red', 'blue') returns 'blue, red, red'. The plain string search has no option that makes it replace every occurrence in one call.

To replace all occurrences using a regular expression, add the global flag g:

const colors = 'red, red, red';
const allBlue = colors.replace(/red/g, 'blue');

console.log(allBlue); // blue, blue, blue

Regular expressions can also combine global matching with other flags. For instance, 'Cat cat CAT'.replace(/cat/gi, 'dog') returns 'dog dog dog': i ignores letter case, while g finds every match. Without g, only the first match is replaced, even if the regular expression matches the same pattern later in the text.

Use the global flag when you truly want every match. If you need to replace only the first occurrence, a string search or a non-global regular expression is clearer and avoids extra pattern syntax.

Using regular expressions for patterns

A regular expression can match more than one exact word. It can describe categories of characters, repeated characters, or boundaries. For example, 'Item 42'.replace(/[0-9]+/, '#') returns 'Item #'; [0-9]+ matches one or more digits. With g, the pattern can replace each separate sequence of digits.

Regular expressions are helpful when the input varies but follows a recognizable rule. This example removes whitespace at the start or end of a string:

const padded = '   hello   ';
const trimmed = padded.replace(/^\s+|\s+$/g, '');

console.log(trimmed); // hello

For ordinary whitespace removal, the built-in trim() method is usually simpler: padded.trim(). This illustrates a useful principle: use a regular expression when its pattern expresses the task, but prefer a direct string method when one already describes the operation.

Some characters have special meanings in regular expressions. A dot, for example, matches almost any character rather than a literal period. If a search pattern comes from user input and must be treated literally, escape regular-expression metacharacters before constructing a pattern; otherwise input such as a.b could match more than the exact text. A plain string search avoids that issue when pattern matching is unnecessary.

Replacement strings and special tokens

When the replacement argument is a string, certain dollar-sign sequences have special meanings. These let a replacement refer to parts of the match rather than inserting the replacement text exactly as typed.

  • $$ inserts a literal dollar sign.
  • $& inserts the entire matched text.
  • $` inserts the portion of the input before the match.
  • $' inserts the portion after the match.
  • $1, $2, and so on insert text captured by numbered groups in the regular expression.
  • $<name> inserts a named capture group when the pattern defines one.

For example, '2026-11-03'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1') returns '11/03/2026'. The parentheses capture the year, month, and day, and the replacement rearranges those captured pieces. Without matching capture groups, numbered tokens do not provide useful captured text.

These tokens apply to a replacement string. If you need a literal sequence such as $& to appear unchanged, the replacement-string rules may be surprising. A replacement function is a straightforward alternative because its returned string is inserted as the result rather than interpreted for these replacement patterns.

Using a function as the replacement

Pass a function when the replacement depends on the match, needs calculation, or must be built dynamically. JavaScript calls the function for each match and uses its return value as the replacement. The first callback argument is the matched text; capture groups follow it, then the match position and the full input string. With named capture groups, an additional groups object is supplied at the end.

const sentence = 'There are 7 cats and 12 dogs.';
const withDoubledNumbers = sentence.replace(/\d+/g, match => String(Number(match) * 2));

console.log(withDoubledNumbers); // There are 14 cats and 24 dogs.

Because the regular expression is global, the callback runs once for each number. The callback converts the matched digits to a number, doubles it, and converts the result back to a string. If a callback returns a number or another non-string value, JavaScript converts that return value to a string for the replacement.

A callback also helps avoid accidentally triggering replacement-string tokens. For example, text.replace(pattern, () => '$&') inserts the literal characters $& as the callback result, rather than using them to mean “insert the match.” The callback signature can be useful for more advanced transformations, but for a simple fixed replacement, a string is easier to read.

replace() compared with replaceAll()

replaceAll() is the built-in choice when the intention is to replace every occurrence of a literal string. For example, 'a+b+a'.replaceAll('+', '-') returns 'a-b-a'. Unlike a regular expression, the plus sign in this example is treated as ordinary text, not as a pattern operator.

Use replace() when you want only the first literal match, when you need regular-expression matching, or when you want to use a replacement callback. Choose replaceAll() for every occurrence of literal text without writing a regular expression. When replaceAll() receives a regular expression, that expression must have the global g flag; otherwise it throws a TypeError.

Both methods return a new string and leave the source value unchanged. They are not interchangeable in every case: a global regular expression with replace() can match a pattern, while a literal argument to replaceAll() is often the clearest option for user-provided text. These methods are part of modern JavaScript; if supporting an older JavaScript environment, check that environment’s compatibility before relying on replaceAll().

Common mistakes and practical guidance

  • Expecting the original variable to change: save the returned value, such as text = text.replace(...), if later code should use the updated string.
  • Expecting a string search to replace every match: use replaceAll() for literal text or a regular expression with g.
  • Forgetting case sensitivity: plain string searches distinguish uppercase and lowercase. Use a case-insensitive regular expression only when that behavior is intended.
  • Confusing a pattern with literal text: regex punctuation such as ., +, and * has special meanings. Use a string search or escape dynamic input if exact matching is required.
  • Misreading dollar tokens: replacement strings interpret sequences such as $& and $1. Return the intended text from a callback when those characters need to remain literal.

For data that can contain line breaks or characters outside basic English letters, test the expression against representative inputs. Regular-expression shorthand and boundaries have specific matching rules, and a pattern that works for a simple example may not cover every language or formatting convention. Avoid using a broad replacement to “sanitize” untrusted data for HTML, SQL, or another output format; those contexts require appropriate escaping or APIs designed for that purpose.

Frequently Asked Questions

Does JavaScript replace() change the original string?
No. Strings are immutable, and replace() returns the result. Assign that result to a variable if you want to use the changed text later.

How do I replace all occurrences of a word?
Use replaceAll('word', 'new word') for literal text, or replace(/word/g, 'new word') when you need a regular expression. The g flag is what makes a regex replace every match.

How can I make replace() ignore capitalization?
Use the regular-expression i flag, for example text.replace(/hello/i, 'hi'). Add g as well if all case-insensitive matches should be replaced.

Can replace() use a function?
Yes. A callback receives the match and, when applicable, captured groups and position information. Its return value becomes the replacement, which is useful for calculated or context-dependent changes.

Why does replace() change only one occurrence?
A plain string search replaces only its first occurrence, and a regular expression without g does the same. Use replaceAll() for a literal global replacement or add g to the regular expression.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.