40

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:

Now I want to know, which one is correct (standard)? Do I need to escape dash character in regex?

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89

2 Answers2

58

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"
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
11

- may have a meaning only inside a character class [], so when you're outside of it you don't need to escape -

Nas Banov
  • 28,347
  • 6
  • 48
  • 67
Gavriel
  • 18,880
  • 12
  • 68
  • 105