Say I have the following url:
How can I create a regex that will match any url starting with that url segment above?
For example:
(should match)
(should match)
(should match)
(should not match)
(should not match)
(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.
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.
5 Answers
Reset to default 13The ^
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(?:$|/)")
Why a regex if your search term is constant?
if (str.substr(0, 22) == 'http://example.com/api') console.log('OK');
^http:\/\/example\.com\/api.*
Regex link
Since it's javascript you can try this
var str = "You should match this string that starts with";
var res = str.match(/^You should match.*/);
alert(res);
You can use an 'anchor' to match the start (or end) of a string.
More info: http://www.regular-expressions.info/anchors.html
new RegExp
argument !=/pattern/
) – Elias Van Ootegem Commented Sep 19, 2014 at 9:19