regexUnnecessaryCharacterClasses
Reports character classes that wrap a single element that does not require brackets.
✅ This rule is included in the ts logical 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.
Examples
Section titled “Examples”Single Character Class
Section titled “Single Character Class”A character class with a single character can be unwrapped.
const pattern = /[a]/;const pattern = /a/;Escape Sequence Class
Section titled “Escape Sequence Class”A character class with a single escape sequence can be unwrapped.
const pattern = /[\d]/;const pattern = /\d/;RegExp Constructor
Section titled “RegExp Constructor”The rule also checks regex patterns in RegExp constructor calls.
const pattern = new RegExp("[a]");const pattern = new RegExp("a");Valid Cases
Section titled “Valid Cases”These cases are valid and will not be reported:
// Negated classesconst negated = /[^a]/;
// Backspace escape (has special meaning in character class)const backspace = /[\b]/;
// Multiple elementsconst multiple = /[ab]/;
// Character rangesconst range = /[a-z]/;
// Equals sign (commonly used in regex for readability)const equals = /[=]/;Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.