index.js 943 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. const escapeStringRegexp = require('escape-string-regexp');
  3. const mapping = require('./lib/mappings');
  4. const hasFlags = (regexFlags, replaceFlags) => {
  5. if (!replaceFlags) {
  6. return true;
  7. }
  8. // Check if every flag in the replace flags is part of the original regex flags
  9. return replaceFlags.split('').every(flag => regexFlags.includes(flag));
  10. };
  11. module.exports = (regexp, flags) => {
  12. flags = flags || '';
  13. if (typeof regexp !== 'string') {
  14. throw new TypeError(`Expected regexp to be of type \`string\`, got \`${typeof regexp}\``);
  15. }
  16. if (typeof flags !== 'string') {
  17. throw new TypeError(`Expected flags to be of type \`string\`, got \`${typeof flags}\``);
  18. }
  19. for (const replace of mapping) {
  20. const key = replace[0];
  21. const replacement = replace[1];
  22. if (hasFlags(flags, replacement.flags)) {
  23. regexp = regexp.replace(new RegExp(escapeStringRegexp(key), 'g'), replacement.value);
  24. }
  25. }
  26. return regexp;
  27. };