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 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.

const pattern = /[a]/;

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

const pattern = /[\d]/;

The rule also checks regex patterns in RegExp constructor calls.

const pattern = new RegExp("[a]");

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.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.