The URLPattern()
constructor returns a new URLPattern
object representing the url pattern defined by the parameters.
new URLPattern(input)
new URLPattern(input, baseURL)
new URLPattern(input, options)
new URLPattern(input, baseURL, options)
let pattern1 = new URLPattern("https://example.com/books/:id");
let pattern2 = new URLPattern("/books/:id", "https://example.com");
let pattern3 = new URLPattern({
protocol: "https",
hostname: "example.com",
pathname: "/books/:id",
});
let pattern4 = new URLPattern({
pathname: "/books/:id",
baseURL: "https://example.com",
});
let pattern = new URLPattern({
protocol: "http{s}?",
hostname: ":subdomain.example.com",
});
let pattern = new URLPattern({
protocol: "http{s}?",
username: ":username",
password: ":password",
hostname: ":subdomain.example.com",
port: ":port(80|443)",
pathname: "/:path",
search: "*",
hash: "*",
});
const pattern = new URLPattern("https://example.com/2022/feb/*");
console.log(pattern.test("https://example.com/2022/feb/xc44rsz"));
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz"));
Setting the ignoreCase
option to true
in the constructor switches all matching operations to case-insensitive for the given pattern:
const pattern = new URLPattern("https://example.com/2022/feb/*", {
ignoreCase: true,
});
console.log(pattern.test("https://example.com/2022/feb/xc44rsz"));
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz"));
The URLPattern
constructor's input pattern can take two forms — a pattern object, or a pattern string and optional baseURL.
new URLPattern(obj);
new URLPattern(pattern);
new URLPattern(pattern, baseURL);
The first type of constructor takes an object that describes the URLs that should be matched by specifying patterns for each individual URL part. Its members can be any of protocol
, username
, password
, hostname
, port
, pathname
, search
, hash
, or baseURL
. If the baseURL
property is provided it will be parsed as a URL and used to populate any other properties that are missing. If the baseURL
property is missing, then any other missing properties default to the pattern *
wildcard, accepting any input.
The second type of constructor takes a URL string that contains patterns embedded in it. The URL string may be relative if a baseURL
is provided as the second argument. Note that it may be necessary to escape some characters in the URL string if it is ambiguous whether the character is separating different URL components or is part of a pattern. For example, you must write about\\:blank
to indicate that the :
is the protocol suffix and not the start of a :blank
named group pattern.