sazr
sazr

Reputation: 25928

Regular Expression Has Syntax Error in Javascript Only

I am attempting to use a regular expression in Javascript but I am getting an error:

SyntaxError: Invalid quantifier ?.

The weird thing is that this exact regular expression works on this website. But when executed in javascript it fails?

Paste this ^/courses(/[a-z0-9\-]+){2,3}(/|\.jsp)?(\?.*)?$ into the website and see it works.

What am I doing wrong?

var res = "/courses/applied-finance-postgraduate-qualifications/graduate-certificate-in-corporate-finance-3/?stid=b951f"
.replace( new RegExp("^/courses(/[a-z0-9\-]+){2,3}(/|\.jsp)?(\?.*)?$"), "abc");

Upvotes: 2

Views: 173

Answers (1)

Felix Kling
Felix Kling

Reputation: 816364

What am I doing wrong?

The regular expression you are creating is

^/courses(/[a-z0-9-]+){2,3}(/|.jsp)?(?.*)?$
                                    ^^^^^

Note the (? part, which is illegal (and hence the error).

\ is the escape character in string literals and regular expression. The parser doesn't know that there is a regular expression in the string literal, the \ is evaluated as part of the string literal, so \? becomes ?. Simple test:

> "\?"
"?"

You have the same problem with \.jsp, which becomes .jsp. The . is not illegal at that position, but it will match every character instead of a ..

If you want to pass it along to the regular expression, you have to escape it:

"^/courses(/[a-z0-9\\-]+){2,3}(/|\\.jsp)?(\\?.*)?$"
                                 ^        ^

Or you simple you use an expression literal (which requires you do escape the / though):

.replace(/^\/courses(\/[a-z0-9-]+){2,3}(\/|\.jsp)?(\?.*)?$/, "abc");

Upvotes: 5

Related Questions