JavaScript Regular Expression Hyphen, or Dash
In a JavaScript regular expression the hyphen (also commonly referred to as the dash) can serve two purposes, depending upon where it is used in the expression.
First, a hyphen can be used as part of a regular expression if the hyphen needs to be found literally. An example of this is a regular expression that looks for a phone number match, such as:
/^d{3}-\d{3}-\d{4}$/
In the preceding example, the hyphen is searched for literally as a separator in the phone number.
A hyphen can also be used as part of a character class to define a range of characters. Expanding upon the phone number regular expression above as an example:
/^[2-9]\d{2}-\d{3}-\d{4}$/
This regular expression has now been updated to specify that the first character must be a number in the 2 to 9 range. Another common use of the hyphen to define a range of characters is:
[A-Za-z0-9] which matches any letter or number character.
It should also be noted that even within a character class the hyphen is only used as a range character if it is between two characters that define as range. That is, if a character class has a hyphen in it that does not define a range, it is then treated as a literal hyphen, just as it would be outside a character class.
Related articles:
JavaScript Regular Expressions
March 9, 2010 at 10:11 pm
Not bad article, but I really miss that you didn’t express your opinion, but ok you just have different approach