Invalid regular expression Range out of Order Error in JS

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
2 min

banner

# 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 = 'bobbyhadz 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));

syntaxerror invalid regular expression range out of order

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.

# Specify the hyphen as the first or last character

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 = 'bobbyhadz 123'; // ✅ specified hyphen as the first character console.log(/[-a-zA-Z0-9 ]/g.test(str)); // 👉️ true

specify hyphen as first or last character

The code for this article is available on GitHub

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

# Escaping the hyphen with a backslash

Alternatively, you can use a backslash \ character to escape the hyphen.

index.js
const str = 'bobbyhadz 123'; console.log(/[a\--zA-Z0-9 ]/g.test(str)); // 👉️ true

escaping hyphen with backslash

Backslashes are used to treat special characters as literal characters.

However, the syntax in the square brackets is difficult to read and unnecessary.

A much better option is to specify the hyphen as the first character in the character class.

index.js
const str = 'bobbyhadz 123'; // ✅ specified hyphen as the first character console.log(/[-a-zA-Z0-9 ]/g.test(str)); // 👉️ true
The code for this article is available on GitHub
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.

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.