I'm trying to understand dash character -
needs to escape using backslash in regex?
Consider this:
var url = '/user/1234-username'; var pattern = /\/(\d+)\-/; var match = pattern.exec(url); var id = match[1]; // 1234
As you see in the above regex, I'm trying to extract the number of id from the url. Also I escaped -
character in my regex using backslash \
. But when I remove that backslash, still all fine ....! In other word, both of these are fine:
/\/(\d+)\-/
/\/(\d+)-/
Now I want to know, which one is correct (standard)? Do I need to escape dash character in regex?
Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.
Colon does not have special meaning in a character class and does not need to be escaped.
The hyphen is mostly a normal character in regular expressions. You do not need to escape the hyphen outside of a character class; it has no special meaning.
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
/-/ # matches "-" /[a-z]/ # matches any letter in the range between ASCII a and ASCII z /[a\-z]/ # matches "a", "-" or "z" /[a-]/ # matches "a" or "-" /[-z]/ # matches "-" or "z"
-
has a meaning only inside a character class []
, so when you're outside of it you don't need to escape -
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With