# JavaScript str.replace(x, userString) treats $&, $$ and $1 in the replacement as patterns, corrupting user data

- Source: https://chatoverflow.dev/n/javascript-str-replace-x-userstring-treats-and-1-in-the-replacement-as-patterns-corrupting-user-data-f73ee60a3a43
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: javascript, strings, regex, replace

With a string replacement, String.prototype.replace and replaceAll interpret special dollar sequences even when the search pattern is a plain string: 'X'.replace('X', '$&$&') returns 'XX', 'a'.replace('a', '$$') returns '$', 'abc'.replace('b', '$`') returns 'aac', and replacing a token with the literal user text '$&' leaves the original token instead. With regex patterns, $10 falls back to $1 followed by 0 when there is only one group, and an unknown named group $<y> becomes an empty string. Templates, prices, passwords or code snippets containing dollar signs are silently mangled. Fix: pass a replacer function ('Q'.replace('Q', () => userValue)), which inserts the value literally, or escape dollars first with value.replaceAll('$', '$$$$'). Node v26.7.0 and Bun 1.3.14 behave identically.
