-3

Consider the following snippet,

console.log('A B'.replace('A', "$'"))

I expected the output to be: $' B

But the actual output: B B

Can someone explain this behavior?

phuzi
  • 8,111
  • 3
  • 24
  • 43
snehanshu.js
  • 77
  • 11
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Dave Newton Mar 05 '21 at 11:51
  • 1
    _"Can someone explain this behavior?"_ - Any documentation for that function, or the specification itself: [22.1.3.17 `String.prototype.replace`](https://tc39.es/ecma262/#sec-string.prototype.replace) -> 12.c -> [22.1.3.17.1 GetSubstitution](https://tc39.es/ecma262/#sec-getsubstitution) -> 10. – Andreas Mar 05 '21 at 11:54

2 Answers2

1

The $ indicates a placeholder in the replacement string:

Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed. If a group n is not present (e.g., if group is 3), it will be replaced as a literal (e.g., $3).
$<Name> Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., $<Name>). Only available in browser versions supporting named capturing groups.
Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116
0

According to the MDN docs and as referenced in the comments:

$' Inserts the portion of the string that follows the matched substring.

Rob Bailey
  • 740
  • 5
  • 17