regexp.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const RE_REGEXP_CHAR = /[\\^$.*+?()[\]{}|]/gu
  2. const RE_HAS_REGEXP_CHAR = new RegExp(RE_REGEXP_CHAR.source)
  3. const RE_REGEXP_STR = /^\/(.+)\/(.*)$/u
  4. /**
  5. * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
  6. * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
  7. *
  8. * @param {string} string The string to escape.
  9. * @returns {string} Returns the escaped string.
  10. */
  11. function escape (string) {
  12. return (string && RE_HAS_REGEXP_CHAR.test(string))
  13. ? string.replace(RE_REGEXP_CHAR, '\\$&')
  14. : string
  15. }
  16. /**
  17. * Convert a string to the `RegExp`.
  18. * Normal strings (e.g. `"foo"`) is converted to `/^foo$/` of `RegExp`.
  19. * Strings like `"/^foo/i"` are converted to `/^foo/i` of `RegExp`.
  20. *
  21. * @param {string} string The string to convert.
  22. * @returns {string} Returns the `RegExp`.
  23. */
  24. function toRegExp (string) {
  25. const parts = RE_REGEXP_STR.exec(string)
  26. if (parts) {
  27. return new RegExp(parts[1], parts[2])
  28. }
  29. return new RegExp(`^${escape(string)}$`)
  30. }
  31. module.exports = {
  32. escape,
  33. toRegExp
  34. }