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. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "Disallow division operators explicitly at the beginning of regular expressions",
  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. };