MCPcopy
hub / github.com/slevithan/xregexp / copyRegex

Function copyRegex

src/xregexp.js:166–218  ·  view source on GitHub ↗

* Copies a regex object while preserving extended data and augmenting with `XRegExp.prototype` * properties. The copy has a fresh `lastIndex` property (set to zero). Allows adding and removing * flags g and y while copying the regex. * * @private * @param {RegExp} regex Regex to copy. * @param

(regex, options)

Source from the content-addressed store, hash-verified

164 * @returns {RegExp} Copy of the provided regex, possibly with modified flags.
165 */
166function copyRegex(regex, options) {
167 if (!XRegExp.isRegExp(regex)) {
168 throw new TypeError('Type RegExp expected');
169 }
170
171 const xData = regex[REGEX_DATA] || {};
172 let flags = getNativeFlags(regex);
173 let flagsToAdd = '';
174 let flagsToRemove = '';
175 let xregexpSource = null;
176 let xregexpFlags = null;
177
178 options = options || {};
179
180 if (options.removeG) {flagsToRemove += 'g';}
181 if (options.removeY) {flagsToRemove += 'y';}
182 if (flagsToRemove) {
183 flags = flags.replace(new RegExp(`[${flagsToRemove}]+`, 'g'), '');
184 }
185
186 if (options.addG) {flagsToAdd += 'g';}
187 if (options.addY) {flagsToAdd += 'y';}
188 if (flagsToAdd) {
189 flags = clipDuplicates(flags + flagsToAdd);
190 }
191
192 if (!options.isInternalOnly) {
193 if (xData.source !== undefined) {
194 xregexpSource = xData.source;
195 }
196 // null or undefined; don't want to add to `flags` if the previous value was null, since
197 // that indicates we're not tracking original precompilation flags
198 if (xData.flags != null) {
199 // Flags are only added for non-internal regexes by `XRegExp.globalize`. Flags are never
200 // removed for non-internal regexes, so don't need to handle it
201 xregexpFlags = flagsToAdd ? clipDuplicates(xData.flags + flagsToAdd) : xData.flags;
202 }
203 }
204
205 // Augment with `XRegExp.prototype` properties, but use the native `RegExp` constructor to avoid
206 // searching for special tokens. That would be wrong for regexes constructed by `RegExp`, and
207 // unnecessary for regexes constructed by `XRegExp` because the regex has already undergone the
208 // translation to native regex syntax
209 regex = augment(
210 new RegExp(options.source || regex.source, flags),
211 hasNamedCapture(regex) ? xData.captureNames.slice(0) : null,
212 xregexpSource,
213 xregexpFlags,
214 options.isInternalOnly
215 );
216
217 return regex;
218}
219
220/**
221 * Converts hexadecimal to decimal.

Callers 2

XRegExpFunction · 0.85
xregexp.jsFile · 0.85

Calls 4

getNativeFlagsFunction · 0.85
clipDuplicatesFunction · 0.85
augmentFunction · 0.85
hasNamedCaptureFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…