Invalid regular expression Range out of Order Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Artem Sapegin

Invalid regular expression Range out of Order Error #

The "Invalid regular expression: Range out of order in character class" error occurs when we forget to escape a hyphen in a character class in a regular expression. To solve the error, specify the hyphen as the first or last character in the regex or escape it.

invalid regular expression range out of order

Here's an example of how the error occurs.

index.js
const str = 'hello 123'; console.log(/[a--zA-Z0-9 ]/g.test(str));

Notice that we have 2 hyphens next to one another in the character class.

This error occurs very often when using regex strings, which are quite more difficult to debug as IDE support is minimal.

To solve the error, you can either add the hyphen as the first or last character in the character class or escape it.

index.js
const str = 'hello 123'; console.log(/[-a-zA-Z0-9 ]/g.test(str));

We added the hyphen as the first character in the character class where it can't be mistaken as a separator of a range.

If you can't spot where the error occurs, use an online regex validator.

The "Explanation" column to the right shows where the errors in the regex occur.

Use the search field on my Home Page to filter through my more than 1,000 articles.