...

View Full Version : question about the regular expression



chickentulip
08-22-2011, 09:16 PM
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>

jmrker
08-22-2011, 09:40 PM
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.
:)

chickentulip
08-22-2011, 09:43 PM
thank you. I kind of suspected that \ were needed for escaping, but wanted to make sure.

devnull69
08-22-2011, 09:45 PM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum