Web Analytics Made Easy -
StatCounter question about the regular expression - CodingForum

Announcement

Collapse
No announcement yet.

question about the regular expression

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new 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
    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.

    Comment


    • #3
      thank you. I kind of suspected that \ were needed for escaping, but wanted to make sure.

      Comment


      • #4
        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.

        Comment

        Working...
        X
        😀
        🥰
        🤢
        😎
        😡
        👍
        👎