Last updated: Mar 2, 2024
Reading time·2 min
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.
Here's an example of how the error occurs.
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));
Notice that we have 2 hyphens next to one another in the character class.
To solve the error, you can either add the hyphen as the first or last character in the character class or escape it.
const str = 'bobbyhadz 123'; // ✅ specified hyphen as the first character 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.
Alternatively, you can use a backslash \
character to escape the hyphen.
const str = 'bobbyhadz 123'; console.log(/[a\--zA-Z0-9 ]/g.test(str)); // 👉️ true
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.
const str = 'bobbyhadz 123'; // ✅ specified hyphen as the first character console.log(/[-a-zA-Z0-9 ]/g.test(str)); // 👉️ true
The "Explanation" column to the right shows where the errors in the regex occur.