Invalid regular expression Range out of Order Error in JS

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Invalid regular expression Range out of Order Error in JS #

The "SyntaxError: 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'; // ⛔️ SyntaxError: Invalid regular expression: /[a--zA-Z0-9 ]/: Range out of order in character class console.log(/[a--zA-Z0-9 ]/g.test(str));

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

The 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)); // 👉️ true

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.

Conclusion #

The "SyntaxError: 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.