Empty class

When do I get this error?

The "Empty class" error is thrown when JSLint, JSHint (only versions before 1.0.0) or ESLint encounters a regular expression literal containing an empty character class. The following example defines a regular expression including an empty character class:

var r = /^abc[]/;

Why do I get this error?

This error is raised to highlight code that may not work as you expect it to. According to the regular expression grammar in the ECMAScript standard, empty character classes are allowed (ES5 A.7):

CharacterClass ::
    [ [lookahead ∉ {^}] ClassRanges ]
    [ ^ ClassRanges ]

ClassRanges ::
    [empty]
    NonemptyClassRanges

However, an empty character class can never match anything, meaning the regular expression in the example above will always fail to match. Since it's unlikely you intended such behaviour, a warning is raised to highlight the fact that you may have overlooked something, or simply made a small typo.

There is no JSLint or JSHint option that can be set to surpress this error. The best way to resolve it is to simply remove any empty character classes from the regular expressions in question:

var r = /^abc/;

However, if you really do need an empty character class, you can use the RegExp constructor to create your regular expression:

var r = new RegExp("^abc[]");

In ESLint the rule that generates this warning is named no-empty-class. You can disable it by setting it to 0, or enable it by setting it to 1.


About the author

James Allardice

This article was written by James Allardice, Software engineer at Tesco and orangejellyfish in London. Passionate about React, Node and writing clean and maintainable JavaScript. Uses linters (currently ESLint) every day to help achieve this.