Skip to content

Prefer String#startsWith() & String#endsWith() over RegExp#test() ​

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Prefer String#startsWith() and String#endsWith() over using a regex with /^foo/ or /foo$/.

This rule is fixable, unless the matching object is known not a string.

Fail ​

js
const foo = /^bar/.test(baz);
js
const foo = /bar$/.test(baz);

Pass ​

js
const foo = baz.startsWith('bar');
js
const foo = baz.endsWith('bar');
js
const foo = baz?.startsWith('bar');
js
const foo = (baz ?? '').startsWith('bar');
js
const foo = String(baz).startsWith('bar');
js
const foo = /^bar/i.test(baz);

Released under the Apache License 2.0.