In the code below I expected the string ‘/?_escaped_fragment_=/faq’ to be converted to ‘/seo/faq’.
Instead of this, I am getting ‘/?/seo/faq’. What is wrong with the code?
var url = '/?_escaped_fragment_=/';
var rule = new RegExp('/?_escaped_fragment_=(.*)');
alert(url.replace(rule,'/seo/$1')); // this shows up '/?/seo//'
2
Answers
You have to escape the
?
because it signifies that the previous character or group is optional.Refer to this Explanation on RegEx101.com:
This is the RegEx you need:
Note: in a
RegExp
constructor, escaping works with\
, not with, because the double backslash is parsed as a single backslash in the string that you pass to the constructor and only then the regular expression even has that single backslash. If you only write one backslash, that one is consumed upon parsing it as a string, resulting in no backslashes for the regular expression.
Also, a
/
doesn’t need to be escaped in the string form, as this is automatically handled.If it’s going to be static anyway, you can simply use a RegEx literal:
?
matches 0 or 1 of the preceding selector. You need to escape the?
with a backslash for the regex, and then escape the backslash for the string:These double escaping problems are a product of using regular expression syntax within a string literal. Might as well save a few characters and use a regex literal: