Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Oct 2010
    Location
    Toronto
    Posts
    95
    Thanks
    52
    Thanked 0 Times in 0 Posts

    question about the regular expression

    The following code removes the brackets and a dash from the string variable.
    I am interested why there are \ in front of each bracket in the regular expression regexp?
    The code work fine if regexp would be /()-/g;
    So why then / is necessary? I would appreciate a lot with someone could explain.
    Thank you very much.

    <html>
    <head>
    <title>Regular Expressions</title>
    <script type="text/javascript">
    var string="(304)434-5454";
    regexp=/[\(\)-]/g;
    document.write(string.replace(regexp, ""));
    </script>
    </head>
    <body>
    </body>
    </html>

  • #2
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,077
    Thanks
    38
    Thanked 498 Times in 492 Posts
    The ( and ) have a special meaning when forming a regex expression.
    They need to be escaped with the \ character so they are treated as true parentheses
    rather than being interpreted as a special division in the regex comparison.

    Google "javascript regex" for a more complete explanation.

  • Users who have thanked jmrker for this post:

    chickentulip (08-22-2011)

  • #3
    New Coder
    Join Date
    Oct 2010
    Location
    Toronto
    Posts
    95
    Thanks
    52
    Thanked 0 Times in 0 Posts
    thank you. I kind of suspected that \ were needed for escaping, but wanted to make sure.

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    The code work fine if regexp would be /()-/g;
    Yes it works great, but it only removes the dash

    So why then / is necessary?
    The \ is necessary to remove the special meaning from characters inside regular expressions. The parts of regular expression surrounded by parentheses are called "groups". If you want the regular expression to match the brackets instead, you have to put \ in front of them (i.e. you have to escape them).

    The angular brackets [] keep their special meaning which is "any of the characters inside those brackets"

    "/[\(\)-]/g" means:
    Match any of the characters (, ) or - globally in the string. replace() will then remove the matched characters.

  • Users who have thanked devnull69 for this post:

    chickentulip (08-22-2011)


  •  

    Posting Permissions

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