#49: replace() with $&
Topic: strings · Difficulty: ★★
console.log('hello'.replace('ll', '[$&]'));Output
he[ll]o
Why
Inside the replacement string argument of String.prototype.replace(), the sequence $& is a special token meaning 'the entire matched substring' — it lets you wrap or reuse the matched text without knowing it in advance. Here the pattern 'll' matches inside 'hello', and $& is substituted with that exact match, 'll', turning the replacement text '[$&]' into '[ll]'. The result splices that back into the original string in place of the match, giving 'he[ll]o'. Related tokens like $1, $2 refer to captured groups when the pattern is a regex with parentheses.