Do I need to escape dash character in regex? [duplicate]

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?

Answers:

Answer

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"
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.