Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
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 = '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.
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 = '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.
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.