Javascript + Regex = Nothing to repeat error? Javascript + Regex = Nothing to repeat error? javascript javascript

Javascript + Regex = Nothing to repeat error?


You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

"[\\[\\]?*+|{}\\\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.


Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:

if (name.search(/[\[\]?*+|{}\\()@.\n\r]/) != -1) {    // ... stuff ...}

Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).


For Google travelers: this stupidly unhelpful error message is also presented when you make a typo and double up the + regex operator:

Okay:

\w+

Not okay:

\w++