skip to Main Content

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//'

http://jsfiddle.net/wLfuuw1p/5/

2

Answers


  1. You have to escape the ? because it signifies that the previous character or group is optional.

    Refer to this Explanation on RegEx101.com:

    /? matches the character / literally

    Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]

    This is the RegEx you need:

    var rule = new RegExp('/\?_escaped_fragment_=(.*)');
    

    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:

    var rule = //?_escaped_fragment_=(.*)/;
    
    Login or Signup to reply.
  2. ? 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:

    var rule = new RegExp('/\?_escaped_fragment_=(.*)');
    

    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:

    var rule = //?_escaped_fragment_=(.*)/;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search