MCPcopy Create free account
hub / github.com/Rich-Harris/magic-string / expandReplacement

Function expandReplacement

src/MagicString.ts:59–135  ·  view source on GitHub ↗

* Expands the `$` substitution patterns that `String.prototype.replace` accepts * in a string replacement. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter * * `captures` holds the capture groups in order, so `ca

(
  replacement: string,
  matched: string,
  position: number,
  str: string,
  captures: (string | undefined)[],
  namedCaptures: Record<string, string | undefined> | undefined,
)

Source from the content-addressed store, hash-verified

57 * value, where there are no groups of either kind.
58 */
59function expandReplacement(
60 replacement: string,
61 matched: string,
62 position: number,
63 str: string,
64 captures: (string | undefined)[],
65 namedCaptures: Record<string, string | undefined> | undefined,
66): string {
67 if (!replacement.includes('$'))
68 return replacement
69
70 let result = ''
71 let index = 0
72
73 while (index < replacement.length) {
74 const dollar = replacement.indexOf('$', index)
75 if (dollar === -1) {
76 result += replacement.slice(index)
77 break
78 }
79
80 result += replacement.slice(index, dollar)
81
82 const char = replacement[dollar + 1]
83 // a `$` that introduces nothing recognisable stands for itself, so consume
84 // only the `$` and reconsider what follows as text
85 let expansion = '$'
86 let consumed = 1
87
88 if (char === '$') {
89 consumed = 2
90 }
91 else if (char === '&') {
92 expansion = matched
93 consumed = 2
94 }
95 else if (char === '`') {
96 expansion = str.slice(0, position)
97 consumed = 2
98 }
99 else if (char === '\'') {
100 expansion = str.slice(position + matched.length)
101 consumed = 2
102 }
103 else if (char === '<' && namedCaptures !== undefined) {
104 const close = replacement.indexOf('>', dollar + 2)
105 if (close !== -1) {
106 // an unknown group name expands to nothing rather than staying literal
107 expansion = namedCaptures[replacement.slice(dollar + 2, close)] ?? ''
108 consumed = close + 1 - dollar
109 }
110 }
111 else if (char >= '0' && char <= '9') {
112 const second = replacement[dollar + 2]
113 const double = second >= '0' && second <= '9' ? Number(char + second) : Number.NaN
114 const single = Number(char)
115
116 // `$nn` only wins over `$n` when it names a group that exists, so `$12`

Callers 3

getReplacementMethod · 0.85
_replaceStringMethod · 0.85
_replaceAllStringMethod · 0.85

Calls 1

sliceMethod · 0.45

Tested by

no test coverage detected