regexp.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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, String.raw`\$&`)
  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 {RegExp} 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. /**
  32. * Checks whether given string is regexp string
  33. * @param {string} string
  34. * @returns {boolean}
  35. */
  36. function isRegExp(string) {
  37. return RE_REGEXP_STR.test(string)
  38. }
  39. module.exports = {
  40. escape,
  41. toRegExp,
  42. isRegExp
  43. }