no-div-regex.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * @fileoverview Rule to check for ambiguous div operator in regexes
  3. * @author Matt DuVall <http://www.mattduvall.com>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "disallow division operators explicitly at the beginning of regular expressions",
  14. category: "Best Practices",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/no-div-regex"
  17. },
  18. fixable: "code",
  19. schema: [],
  20. messages: {
  21. unexpected: "A regular expression literal can be confused with '/='."
  22. }
  23. },
  24. create(context) {
  25. const sourceCode = context.getSourceCode();
  26. return {
  27. Literal(node) {
  28. const token = sourceCode.getFirstToken(node);
  29. if (token.type === "RegularExpression" && token.value[1] === "=") {
  30. context.report({
  31. node,
  32. messageId: "unexpected",
  33. fix(fixer) {
  34. return fixer.replaceTextRange([token.range[0] + 1, token.range[0] + 2], "[=]");
  35. }
  36. });
  37. }
  38. }
  39. };
  40. }
  41. };