Results 1 to 5 of 5

Thread: RegExp behaviour

  1. #1
    Join Date
    Aug 2009

    RegExp behaviour

    I have a code snippet which parses the url and returns some information after the occurrence of ? in the url:
    function getValue(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if(results == null)
      return "";
      return results[1];
    If the function is called as getValue("params"); then the entire url is parsed until ?params= is found and what ever follows after that is returned.
    I can also see that if the function is called as getValue("[params]"); then the line:
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    makes name as \[params\]

    Now my question is
    1. What significance does [ or ] character have in JS. Why are they escaped?
    2. What is being achieved by the line var regexS = "[\\?&]"+name+"=([^&#]*)";
    why are we appending so many characters to name?

  2. #2
    Join Date
    Nov 2008
    I'll answer to yout 1st question.

    "[xyz]" in RegExp is a character set, it matches any of the encolsed characters. You can spcify a range of charcters like from "A" to "Z" by using aa hyphen like this "[A-Z]".

    Example: To match any of the alphabet letters you can use this.. "[A-Za-z]".

    If you use it like this "[^xyz]" then it matches any of the characters that are not enclosed in this charcter set.

    Hope I helped.

  3. #3
    Join Date
    Aug 2009
    Oh thanks. It did help.
    How I would also like to know the significance of the [ and ] characters in
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    how is it that if name = [params] then at the end of the above statement execution, name becomes \[params\]

  4. #4
    Join Date
    Aug 2009
    Please read "How I would also like to" as "However I would also like to"

  5. #5
    Join Date
    Aug 2007
    [ is a special character, so when you want to replace [ in a string, you must use \[. Actually, that's not a great replace. This would be better.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center

Recent Articles