index.js 660 B

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