URL "starts with" using regex?

XåpplI'-I0llwlg'I  - picture XåpplI'-I0llwlg'I - · Sep 19, 2014 · Viewed 19.3k times · Source

Say I have the following url:

http://example.com/api

How can I create a regex that will match any url starting with that url segment above?

For example:

http://example.com/api/auth (should match)

http://example.com/api/orders (should match)

http://example.com/api/products (should match)

http://example.com/auth (should not match)

http://examples.com/api/auth (should not match)

https://example.com/api/auth (should not match)

Yes, obviously I could just call string.indexOf(url) == 0 to do a "starts with" check, but I specifically need a regular expression because I have to provide one to a third-party library.

Answer

Joe picture Joe · Sep 19, 2014

The ^ modifier at the start of the expression means "string must start with":

/^http:\/\/example\.com\/api/

If you were using a different language which supports alternative delimiters, then it would probably be worth doing since the URL will contain /s in it. This doesn't work in Javascript (h/t T.J. Crowder) but does in languages like PHP (just mentioning it for completeness):

#^http://example\.com/api#

You could use this in JavaScript, though:

new RegExp("^http://example\\.com/api")

It's also worth noting that this will match http://example.com/apis-are-for-losers/something, because you're not testing for a / after api - just something to bear in mind. To solve that, you can use an alternation at the end requiring either that you be at the end of the string or that the next character be a /:

/^http:\/\/example\.com\/api(?:$|\/)/

new RegExp("^http://example\\.com/api(?:$|/)")