How to Fix "Nothing to repeat" Errors in JavaScript

Ferenc Almasi β€’ 2022 July 16 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

The "Uncaught SyntaxError: Invalid regular expression: Nothing to repeat" error occurs in JavaScript when your regular expression is not valid. In order to fix the error, locate where the error is originating from, and then verify that the regular expression that you are using is valid.

Here are some examples of invalid regular expressions that can commonly occur and might be causing the error in your case too:

Copied to clipboard! Playground
// ❌ Not properly escaping special characters
/.**/ -> /.*\*/

// ❌ Using double plus signs after a word boundary
/w++/ -> /w+/

// ❌ Starting a regex with a quantifier
/?[a-z]/ -> /[a-z]?/
/+[a-z]/ -> /[a-z]+/
  • Make sure you properly escape special characters with a backslash. In the first example, two asterisks are used after each other which invalidates the regex.
  • Verify that you don't accidentally repeat special characters. In the second example, we wanted to use a word boundary, but there is an extra plus sign at the end of the expression that causes a "Nothing to repeat" error.
  • Make sure you don't start your regular expression with a quantifier. In the third example, the quantifier should come only after the character class, not before. Again, this can cause the above error.

As a general rule, "Nothing to repeat" errors occur in JavaScript, whenever you have an invalid regular expression in your code. If you would like to try to experiment with regex, I recommend using regexr.com where matches will be highlighted according to your expression. If you are looking for more resources on Regex, check out one of the resources below.


Resources

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.