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

Method _replaceRegexp

src/MagicString.ts:1117–1168  ·  view source on GitHub ↗

@internal

(searchValue: RegExp, replacement: string | ReplacementFunction)

Source from the content-addressed store, hash-verified

1115
1116 /** @internal */
1117 _replaceRegexp(searchValue: RegExp, replacement: string | ReplacementFunction): this {
1118 function getReplacement(match: RegExpMatchArray, str: string): string {
1119 if (typeof replacement === 'string') {
1120 return replacement.replace(/\$(\$|&|\d+)/g, (_: string, i: string) => {
1121 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1122 if (i === '$')
1123 return '$'
1124 if (i === '&')
1125 return match[0]
1126 const num = +i
1127 if (num < match.length)
1128 return match[+i]
1129 return `$${i}`
1130 })
1131 }
1132 else {
1133 return replacement(match[0], ...match.slice(1), match.index, str, match.groups)
1134 }
1135 }
1136 function matchAll(re: RegExp, str: string): RegExpExecArray[] {
1137 const matches = []
1138 while (true) {
1139 const match = re.exec(str)
1140 if (!match)
1141 break
1142
1143 matches.push(match)
1144 }
1145 return matches
1146 }
1147 if (searchValue.global) {
1148 const matches = matchAll(searchValue, this.original)
1149 matches.forEach((match) => {
1150 if (match.index != null) {
1151 const replacement = getReplacement(match, this.original)
1152 if (replacement !== match[0]) {
1153 this.overwrite(match.index, match.index + match[0].length, replacement)
1154 }
1155 }
1156 })
1157 }
1158 else {
1159 const match = this.original.match(searchValue)
1160 if (match && match.index != null) {
1161 const replacement = getReplacement(match, this.original)
1162 if (replacement !== match[0]) {
1163 this.overwrite(match.index, match.index + match[0].length, replacement)
1164 }
1165 }
1166 }
1167 return this
1168 }
1169
1170 /** @internal */
1171 _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