Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL "starts with" using regex?

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.

like image 234
XåpplI'-I0llwlg'I - Avatar asked Sep 03 '25 02:09

XåpplI'-I0llwlg'I -


2 Answers

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(?:$|/)")
like image 170
Joe Avatar answered Sep 04 '25 20:09

Joe


Why a regex if your search term is constant?

if (str.substr(0, 22) == 'http://example.com/api') console.log('OK');
like image 24
Toto Avatar answered Sep 04 '25 21:09

Toto