Skip to content

regexUnnecessaryCharacterClasses

Reports character classes that wrap a single element that does not require brackets.

✅ This rule is included in the ts logical and logicalStrict presets.

Reports character classes that wrap a single element that does not require brackets. A character class like [a] or [\d] can be simplified to just a or \d.

A character class with a single character can be unwrapped.

AEconsB0patteAE< =sp ansty="le--0:#5CA7E4;--1:#3A68">81<1/sp ansty="le--0:#82AAFF;--1:#3B61">B0[1<1/sp ansty="le--0:#D6DEEB;--1:#403F">5<3;d ivclassNa="meco">
44AEco61B0pat446<88F spans="tyle--0:#D9F5DD;--1:#11">1<111/ spans="tyle--0:#5CA7E4;--1:#3A">6<88Fa spans="tyle--0:#D9F5DD;--1:#11">1<111/ spans="tyle--0:#D6DEEB;--1:#40">3

A character class with a single escape sequence can be unwrapped.

AEconsB0patteAE< =sp ansty="le--0:#5CA7E4;--1:#3A68">81<1/sp ansty="le--0:#82AAFF;--1:#3B61">B0[\1<1/sp ansty="le--0:#D6DEEB;--1:#403F">5<3;d ivclassNa="meco">
44AEco61B0pat446<88F spans="tyle--0:#D9F5DD;--1:#11">1<111/ spans="tyle--0:#82AAFF;--1:#3B">611<111/ spans="tyle--0:#D6DEEB;--1:#40">3<\d/>

The rule also checks regex patterns in RegExp constructor calls.

AEconsB0patteAE <= sp ansty="le--0:#7FDBCA;--1:#096E">72nAB0RegE5<3(sp ansty="le--0:#D9F5DD;--1:#1111">1<1"sp ansty="le--0:#ECC48D;--1:#984E">4D[1<1"sp ansty="le--0:#D6DEEB;--1:#403F">53<);d ivclassNa="meco"><);d>
44AEco61B0pat44A6E7<2new spans="tyle--0:#C792EA;--1:#88">4<4AE spans="tyle--0:#82AAFF;--1:#3B">61B0Re31<111" spans="tyle--0:#ECC48D;--1:#98">41<111" spans="tyle--0:#D6DEEB;--1:#40">3F<53) ;divclass="Name">

These cases are valid and will not be reported:

// Negated classes
const negated = /[^a]/;
// Backspace escape (has special meaning in character class)
const backspace = /[\b]/;
// Multiple elements
const multiple = /[ab]/;
// Character ranges
const range = /[a-z]/;
// Equals sign (commonly used in regex for readability)
const equals = /[=]/;

This rule is not configurable.

If you prefer to use character classes for consistency or readability, even when they contain only a single element, you might prefer to disable this rule.