0

I was studying intro to regex stuff today and I came across this post on SO

to test these patterns: /video/123/slug and /video/123, this regular expression was given:

([^/]+)/([0-9]+)(?:/([^/]+))?

I understand basically how it works, however, it only works when I put it in a constructor regex:

var test1 = new RegExp("([^/]+)/([0-9]+)(?:/([^/]+))?"),
a = "/video/123/slug",
b = "/video/123";
console.log(test1.test(a)); //true

but doing it literally fails:

/([^/]+)/([0-9]+)(?:/([^/]+))?")/.test(a) // all sorts of warnings and an error: Uncaught SyntaxError: Unexpected token ) 

Why is this? http://jsbin.com/idegal/1/edit

2
  • 1
    Escaping of / is needed in the literal version! (Since you start and close the expression with that same character!) Commented Jul 3, 2013 at 5:50
  • 1
    Your /'s are not escaped Commented Jul 3, 2013 at 5:50

1 Answer 1

1

/ acts as a delimiter when you use regex literally..

So,you need to escape it \/.Your regex would be

  /([^\/]+)\/([0-9]+)(?:\/([^\/]+))?")/.test(a)

You don't need to escape it when used within string literal

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks very much. This seems to make regular expressions more complicated when they're literals. Are they frequently done that way? as a string, it seems like there's less to remember, and easier to read. Is this generally correct?
@thomas those are the two syntax to create a regex object...So you can use any1 of it depending on your choice
@thomas: That depends on what you are searching for. Suppose you search for ' and ", or ?: etc.. You'd still need to escape those. The constructor is especially useful to add changing (in a loop or depending on situation) variables into a regex. The literal however is usually treated as a fixed static object. So, both have their place/use and trade-offs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.