Checking URL Patterns
Category: JavaScript
const pattern = new URLPattern({ procotol: "http{s}?", username: ":user?", password: ":password?", hostname: "{:subdomain.}*.mysite.com", pathname: "/post/:id?",});
Usage
pattern.test("http://mysite.com/post/123"); // truepattern.test("https://mysite.com/post/123"); // truepattern.test("https://mysite.com/post"); // truepattern.test("https://mysite.com/post/123/123"); // falsepattern.test("https://mysite.com/posts/"); // falsepattern.test("ws://mysite.com/posts/"); // falsepattern.test("https://example.com/post/123"); // false
Explanation
URLPattern
makes it way easier to test whether a string modeling a URL conforms to a pattern. Additionally, a URLPattern
is specifically designed to test URLs, so you don’t have to deal with regular expressions only to find out whether URLs are correct (pattern-wise).
The API is experimental, though. The following browsers have support for URLPattern
:
- Chrome
- Edge
- Opera
- Chrome Android
- Opera Android
- Samsung Internet
- WebView Android
The following browsers have no support for URLPattern
:
- Firefox
- Safari
- Firefox Android
- Safari iOS