2

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");
0

1 Answer 1

5

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.