String.prototype.replace()
With a string pattern it replaces one occurrence and stops. Replacing every occurrence needs either a /g regex or replaceAll — and the $ characters in your replacement are not literal.
Demo
The first case is the one to internalise: 'a-b-c' with a string pattern becomes 'a+b-c'. One hyphen changed, the second untouched, and nothing warns you. The second case shows the same thing with a word — only the leading 'cat' becomes 'fox'. The fourth case demonstrates that the replacement string is not literal text: $& expands to whatever was matched, so '[$&]' wraps the match in brackets rather than inserting a literal dollar sign and ampersand.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | string | RegExp | yes | A string matches literally and ONCE. A RegExp matches by pattern, and replaces every occurrence only if it carries the g flag. |
| replacement | string | Function | yes | A string, in which $& $1 $` $' and $$ have special meanings. Or a function called with (match, ...groups, offset, string) whose return value is inserted literally. |
Return value
string — A NEW string. Strings are immutable, so the original is never modified — an unassigned replace call does nothing at all.
Common patterns
s.replaceAll('-', '+'); s.replace(/-/g, '+');
'2026-09-17'.replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1');
text.replace(/\d+/g, m => Number(m) * 2);
Examples
Pitfalls
'a-b-c'.replace('-', '+')
'a-b-c'.replaceAll('-', '+')
let s = 'a-b'; s.replace('-', '+'); s
let s = 'a-b'; s = s.replace('-', '+'); s
'x'.replace('x', '$&!')
'x'.replace('x', () => '$&!')
'a.b axb'.replace(new RegExp('a.b', 'g'), '-')
'a.b axb'.replaceAll('a.b', '-')
'aa'.replaceAll(/a/, 'b')
'aa'.replaceAll(/a/g, 'b')
When to use
- Substituting the first occurrence deliberately
- Pattern-based substitution with a RegExp
- Reordering or reformatting with capture groups
- Computing each replacement with a function
- Replacing every occurrence of plain text → replaceAll, which is clearer
- You only want to test for presence → includes
- You want the pieces, not a new string → split
- Building the pattern from user input → escape it, or use a string pattern
Notes
FAQ
Because a string pattern means exactly one replacement — that is the specified behaviour, not a bug. Use replaceAll for plain text, or a regex with the g flag. This has caught nearly everyone at least once.
'a-b-c'.replace('-', '+'); // 'a+b-c' 'a-b-c'.replaceAll('-', '+'); // 'a+b+c'