blob: 24edae6ba549cc4e069bffc220c404892afe9b59 [file] [log] [blame]
Mathias Bynens79e2cf02020-05-29 16:46:17 +02001'use strict';
2const isRegexp = require('is-regexp');
3
4const flagMap = {
5 global: 'g',
6 ignoreCase: 'i',
7 multiline: 'm',
8 dotAll: 's',
9 sticky: 'y',
10 unicode: 'u'
11};
12
13module.exports = (regexp, options = {}) => {
14 if (!isRegexp(regexp)) {
15 throw new TypeError('Expected a RegExp instance');
16 }
17
18 const flags = Object.keys(flagMap).map(flag => (
19 (typeof options[flag] === 'boolean' ? options[flag] : regexp[flag]) ? flagMap[flag] : ''
20 )).join('');
21
22 const clonedRegexp = new RegExp(options.source || regexp.source, flags);
23
24 clonedRegexp.lastIndex = typeof options.lastIndex === 'number' ?
25 options.lastIndex :
26 regexp.lastIndex;
27
28 return clonedRegexp;
29};