index.js 894 B

12345678910111213141516171819202122232425262728293031323334
  1. "use strict";
  2. /**
  3. * RegexParser
  4. * Parses a string input.
  5. *
  6. * @name RegexParser
  7. * @function
  8. * @param {String} input The string input that should be parsed as regular
  9. * expression.
  10. * @return {RegExp} The parsed regular expression.
  11. */
  12. var RegexParser = module.exports = function (input) {
  13. // Validate input
  14. if (typeof input !== "string") {
  15. throw new Error("Invalid input. Input must be a string");
  16. }
  17. // Parse input
  18. var m = input.match(/(\/?)(.+)\1([a-z]*)/i);
  19. // If there's no match, throw an error
  20. if (!m) {
  21. throw new Error("Invalid regular expression format.");
  22. }
  23. // Filter valid flags: 'g', 'i', 'm', 's', 'u', and 'y'
  24. var validFlags = Array.from(new Set(m[3])).filter(function (flag) {
  25. return "gimsuy".includes(flag);
  26. }).join("");
  27. // Create the regular expression
  28. return new RegExp(m[2], validFlags);
  29. };