Dollar Patterns Expand In Replacements

Dollar sequences like $1, $&, and $<name> expand inside replacement strings; function replacements return literal text with no expansion at all.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
// replacement 字符串里 $ 开头的序列会被展开,不是字面文本
const template = 'invoice #1042 total $42.00';

// $& 是整个匹配,$1/$2 是捕获组
console.log(template.replace(/#(\d+)/, 'no. $1 (matched "$&")'));

// 命名捕获组用 $<name> 引用,可读性更好
console.log(template.replace(/#(?<num>\d+)/, 'no. $<num>'));

// 函数形式:返回值不做任何展开,"$&" 想原样输出只能走这条路
console.log(template.replace(/#(\d+)/, (match) => `[$& was ${match}]`));

// 字面美元符号也要写成 $$,否则被当作模式前缀
console.log('price'.replace('price', '$$100'));

// 默认只替换第一处:全局替换要 g 标志或 replaceAll
console.log('a-b-c'.replace(/-/g, '+'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

invoice no. 1042 (matched "#1042") total $42.00
invoice no. 1042 total $42.00
invoice [$& was #1042] total $42.00
$100
a+b+c

Expansion sequences

Inside a string replacement, $& expands to the whole match, $1/$2 to capture groups, and $ to named groups. The demo turns #1042 into no. $1 (matched “$&”) style output through both numbered and named forms.

Literal output needs a function

To print the literal text $& was #1042 the code passes a function replacement — returned strings undergo no expansion, so dollar sequences survive verbatim only on that path.

Escapes and scope

‘$$100’ demonstrates the $$ escape that yields a literal dollar, and the final line contrasts /-/g (all dashes) with the default first-match-only behavior of replace.

Interactive Tools for This Topic

FAQ

How do you output a literal $& in a replacement?
Use a function replacement — returned strings are not scanned for dollar sequences, so the text passes through verbatim.
What does $$ produce in a string replacement?
A single literal dollar sign; a lone $ before a digit or letter is treated as the start of an expansion pattern instead.