Oliver Jumpertz

Checking URL Patterns

Category: JavaScript

Share this snippet to:

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"); // true
pattern.test("https://mysite.com/post/123"); // true
pattern.test("https://me:[email protected]/post/123"); // true
pattern.test("https://mysite.com/post"); // true
pattern.test("https://mysite.com/post/123/123"); // false
pattern.test("https://mysite.com/posts/"); // false
pattern.test("ws://mysite.com/posts/"); // false
pattern.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:

The following browsers have no support for URLPattern:


Share this snippet to: