wrap-regex.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * @fileoverview Rule to flag when regex literals are not wrapped in parens
  3. * @author Matt DuVall <http://www.mattduvall.com>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. description: "require parenthesis around regex literals",
  13. category: "Stylistic Issues",
  14. recommended: false,
  15. url: "https://eslint.org/docs/rules/wrap-regex"
  16. },
  17. schema: [],
  18. fixable: "code"
  19. },
  20. create(context) {
  21. const sourceCode = context.getSourceCode();
  22. return {
  23. Literal(node) {
  24. const token = sourceCode.getFirstToken(node),
  25. nodeType = token.type;
  26. if (nodeType === "RegularExpression") {
  27. const source = sourceCode.getTokenBefore(node);
  28. const ancestors = context.getAncestors();
  29. const grandparent = ancestors[ancestors.length - 1];
  30. if (grandparent.type === "MemberExpression" && grandparent.object === node &&
  31. (!source || source.value !== "(")) {
  32. context.report({
  33. node,
  34. message: "Wrap the regexp literal in parens to disambiguate the slash.",
  35. fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`)
  36. });
  37. }
  38. }
  39. }
  40. };
  41. }
  42. };