diff --git a/README.md b/README.md index 5f5e94c..f68886b 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ Read more at the | [prefer-static-regex](./src/rules/prefer-static-regex.ts) | Prefer defining regular expressions at module scope to avoid re-compilation on every function call | ✅ | ✖️ | 🔶 | | [prefer-inline-equality](./src/rules/prefer-inline-equality.ts) | Prefer inline equality checks over temporary object creation for simple comparisons | ✖️ | ✅ | 🔶 | | [prefer-string-fromcharcode](./src/rules/prefer-string-fromcharcode.ts) | Prefer `String.fromCharCode()` over `String.fromCodePoint()` for code points below `0x10000` | ✅ | ✅ | ✖️ | +| [prefer-includes-over-regex-test](./src/rules/prefer-includes-over-regex-test.ts) | Prefer `s.includes()` / `startsWith` / `endsWith` over `/literal/.test(s)` when the regex has no metacharacters or flags | ✖️ | ✅ | ✖️ | | [no-delete-property](./src/rules/no-delete-property.ts) | Disallow `delete` on properties — V8 deoptimizes the object to dictionary mode | ✖️ | 💡 | ✖️ | ## Sponsors diff --git a/src/main.ts b/src/main.ts index 46e8711..7064671 100644 --- a/src/main.ts +++ b/src/main.ts @@ -23,6 +23,7 @@ import {preferArraySome} from './rules/prefer-array-some.js'; import {preferStaticRegex} from './rules/prefer-static-regex.js'; import {preferInlineEquality} from './rules/prefer-inline-equality.js'; import {banDependencies} from './rules/ban-dependencies.js'; +import {preferIncludesOverRegexTest} from './rules/prefer-includes-over-regex-test.js'; import {noDeleteProperty} from './rules/no-delete-property.js'; import {preferStringFromCharCode} from './rules/prefer-string-fromcharcode.js'; @@ -53,6 +54,7 @@ const plugin: ESLint.Plugin = { 'prefer-static-regex': preferStaticRegex, 'prefer-inline-equality': preferInlineEquality as never as Rule.RuleModule, 'prefer-string-fromcharcode': preferStringFromCharCode, + 'prefer-includes-over-regex-test': preferIncludesOverRegexTest, 'no-delete-property': noDeleteProperty, 'ban-dependencies': banDependencies } diff --git a/src/rules/prefer-includes-over-regex-test.test.ts b/src/rules/prefer-includes-over-regex-test.test.ts new file mode 100644 index 0000000..63c5640 --- /dev/null +++ b/src/rules/prefer-includes-over-regex-test.test.ts @@ -0,0 +1,111 @@ +import {RuleTester} from 'eslint'; +import {preferIncludesOverRegexTest} from './prefer-includes-over-regex-test.js'; + +const ruleTester = new RuleTester({ + languageOptions: { + ecmaVersion: 2022, + sourceType: 'module' + } +}); + +ruleTester.run('prefer-includes-over-regex-test', preferIncludesOverRegexTest, { + valid: [ + // already using string methods + "s.includes('foo');", + "s.startsWith('foo');", + "s.endsWith('foo');", + + // regex with special characters + '/foo.bar/.test(s);', + '/foo+/.test(s);', + '/[abc]/.test(s);', + '/(foo|bar)/.test(s);', + '/\\d/.test(s);', + '/foo\\$/.test(s);', + + // regex with flags (semantics differ) + '/foo/i.test(s);', + '/foo/g.test(s);', + + // empty regex bodies + '/^$/.test(s);', // matches empty — could autofix to s==='' but skipped + '/^/.test(s);', + '/$/.test(s);', + + // wrong receiver / method + 'regex.test(s);', + "s.test('foo');", + '/foo/.exec(s);', + + // .test() with extra args + '/foo/.test(s, extra);', + + // RegExp constructor (not a literal) + "new RegExp('foo').test(s);" + ], + + invalid: [ + // plain — includes + { + code: 'if (/foo/.test(s)) {}', + output: 'if (s.includes("foo")) {}', + errors: [{messageId: 'preferIncludes'}] + }, + + // start anchor — startsWith + { + code: 'if (/^foo/.test(s)) {}', + output: 'if (s.startsWith("foo")) {}', + errors: [{messageId: 'preferStartsWith'}] + }, + + // end anchor — endsWith + { + code: 'if (/foo$/.test(s)) {}', + output: 'if (s.endsWith("foo")) {}', + errors: [{messageId: 'preferEndsWith'}] + }, + + // both anchors — equals + { + code: 'if (/^foo$/.test(s)) {}', + output: 'if (s === "foo") {}', + errors: [{messageId: 'preferEquals'}] + }, + + // numeric/alphanumeric pattern + { + code: '/abc123/.test(s);', + output: 's.includes("abc123");', + errors: [{messageId: 'preferIncludes'}] + }, + + // arg is a call expression — no extra parens + { + code: '/foo/.test(getStr());', + output: 'getStr().includes("foo");', + errors: [{messageId: 'preferIncludes'}] + }, + + // arg is a logical expression — needs parens + { + code: '/foo/.test(a || b);', + output: '(a || b).includes("foo");', + errors: [{messageId: 'preferIncludes'}] + }, + + // arg is a conditional — needs parens, especially for the equals case + { + code: '/^foo$/.test(x ? a : b);', + output: '(x ? a : b) === "foo";', + errors: [{messageId: 'preferEquals'}] + }, + + // double-quoted literal in pattern handled fine + { + code: '/abc/.test(s);', + output: 's.includes("abc");', + errors: [{messageId: 'preferIncludes'}] + } + ] +}); diff --git a/src/rules/prefer-includes-over-regex-test.ts b/src/rules/prefer-includes-over-regex-test.ts new file mode 100644 index 0000000..b8bd35b --- /dev/null +++ b/src/rules/prefer-includes-over-regex-test.ts @@ -0,0 +1,137 @@ +import type {Rule} from 'eslint'; +import type {CallExpression, Expression, RegExpLiteral} from 'estree'; + +function isRegexLiteral(node: Expression): node is RegExpLiteral { + return node.type === 'Literal' && 'regex' in node && node.regex !== undefined; +} + +const SPECIAL_CHARS_RE = /[\\.*+?()[\]{}|^$]/; + +type Kind = 'includes' | 'startsWith' | 'endsWith' | 'equals'; + +function classifyRegex(pattern: string): {kind: Kind; literal: string} | null { + let body = pattern; + let hasStart = false; + let hasEnd = false; + + if (body.startsWith('^')) { + hasStart = true; + body = body.slice(1); + } + // A trailing `$` is the end anchor unless it's preceded by an unescaped `\` + if (body.endsWith('$') && !body.endsWith('\\$')) { + hasEnd = true; + body = body.slice(0, -1); + } + + if (body.length === 0) return null; + if (SPECIAL_CHARS_RE.test(body)) return null; + + let kind: Kind; + if (hasStart && hasEnd) kind = 'equals'; + else if (hasStart) kind = 'startsWith'; + else if (hasEnd) kind = 'endsWith'; + else kind = 'includes'; + + return {kind, literal: body}; +} + +function needsParens(node: Expression): boolean { + switch (node.type) { + case 'Identifier': + case 'Literal': + case 'MemberExpression': + case 'CallExpression': + case 'NewExpression': + case 'ThisExpression': + case 'ArrayExpression': + case 'ObjectExpression': + case 'TemplateLiteral': + case 'TaggedTemplateExpression': + return false; + default: + return true; + } +} + +export const preferIncludesOverRegexTest: Rule.RuleModule = { + meta: { + type: 'suggestion', + docs: { + description: + 'Prefer String.prototype.{includes,startsWith,endsWith} over equivalent regex.test() calls', + recommended: false + }, + fixable: 'code', + schema: [], + messages: { + preferIncludes: + "Prefer `s.includes('{{literal}}')` over `/{{pattern}}/.test(s)`.", + preferStartsWith: + "Prefer `s.startsWith('{{literal}}')` over `/^{{literal}}/.test(s)`.", + preferEndsWith: + "Prefer `s.endsWith('{{literal}}')` over `/{{literal}}$/.test(s)`.", + preferEquals: + "Prefer `s === '{{literal}}'` over `/^{{literal}}$/.test(s)`." + } + }, + create(context) { + const sourceCode = context.sourceCode; + return { + CallExpression(node: CallExpression) { + if (node.callee.type !== 'MemberExpression') return; + if (node.callee.computed) return; + if ( + node.callee.property.type !== 'Identifier' || + node.callee.property.name !== 'test' + ) + return; + if (node.arguments.length !== 1) return; + + const regex = node.callee.object; + if (regex.type !== 'Literal' || !isRegexLiteral(regex)) return; + if (regex.regex.flags !== '') return; + + const cls = classifyRegex(regex.regex.pattern); + if (!cls) return; + + const arg = node.arguments[0]!; + if (arg.type === 'SpreadElement') return; + const argText = needsParens(arg as Expression) + ? `(${sourceCode.getText(arg)})` + : sourceCode.getText(arg); + const literalText = JSON.stringify(cls.literal); + + let replacement: string; + let messageId: string; + switch (cls.kind) { + case 'includes': + replacement = `${argText}.includes(${literalText})`; + messageId = 'preferIncludes'; + break; + case 'startsWith': + replacement = `${argText}.startsWith(${literalText})`; + messageId = 'preferStartsWith'; + break; + case 'endsWith': + replacement = `${argText}.endsWith(${literalText})`; + messageId = 'preferEndsWith'; + break; + case 'equals': + replacement = `${argText} === ${literalText}`; + messageId = 'preferEquals'; + break; + } + + context.report({ + node, + messageId, + data: {literal: cls.literal, pattern: regex.regex.pattern}, + fix(fixer) { + return fixer.replaceText(node, replacement); + } + }); + } + }; + } +};