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

Method _replaceRegexp

src/MagicString.ts:1134–1185  ·  view source on GitHub ↗

@internal

(searchValue: RegExp, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1132
1133 /** @internal */
1134 _replaceRegexp(searchValue: RegExp, replacement: string | ReplacementFunction): this {
1135 function getReplacement(match: RegExpMatchArray, str: string): string {
1136 if (typeof replacement === 'string') {
1137 return replacement.replace(/\$(\$|&|\d+)/g, (_: string, i: string) => {
1138 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1139 if (i === '$')
1140 return '$'
1141 if (i === '&')
1142 return match[0]
1143 const num = +i
1144 if (num < match.length)
1145 return match[+i]
1146 return `$${i}`
1147 })
1148 }
1149 else {
1150 return replacement(match[0], ...match.slice(1), match.index, str, match.groups)
1151 }
1152 }
1153 function matchAll(re: RegExp, str: string): RegExpExecArray[] {
1154 const matches = []
1155 while (true) {
1156 const match = re.exec(str)
1157 if (!match)
1158 break
1159
1160 matches.push(match)
1161 }
1162 return matches
1163 }
1164 if (searchValue.global) {
1165 const matches = matchAll(searchValue, this.original)
1166 matches.forEach((match) => {
1167 if (match.index != null) {
1168 const replacement = getReplacement(match, this.original)
1169 if (replacement !== match[0]) {
1170 this.overwrite(match.index, match.index + match[0].length, replacement)
1171 }
1172 }
1173 })
1174 }
1175 else {
1176 const match = this.original.match(searchValue)
1177 if (match && match.index != null) {
1178 const replacement = getReplacement(match, this.original)
1179 if (replacement !== match[0]) {
1180 this.overwrite(match.index, match.index + match[0].length, replacement)
1181 }
1182 }
1183 }
1184 return this
1185 }
1186
1187 /** @internal */
1188 _replaceString(string: string, replacement: string | ReplacementFunction): this {

Callers 2

replaceMethod · 0.95
replaceAllMethod · 0.95

Calls 1

overwriteMethod · 0.95

Tested by

no test coverage detected