The test()
method of the URLPattern
interface takes a URL or object of URL parts, and returns a boolean indicating if the given input matches the current pattern.
test(input)
test(input, baseURL)
This example shows how to use the test()
method to match a URL against a pattern. The example prints the result of the test()
calls to the console.
const pattern = new URLPattern("http{s}?://*.example.com/books/:id");
console.log(pattern.test("https://store.example.com/books/123"));
console.log(pattern.test("https://example.com/books/123"));
console.log(pattern.test("/books/123", "http://store.example.com"));
console.log(pattern.test("/books/123", "data:text/plain,hello world!"));
console.log(pattern.test("/books/123"));
console.log(
pattern.test({
pathname: "/books/123",
baseURL: "http://store.example.com",
}),
);
console.log(
pattern.test({
protocol: "https",
hostname: "store.example.com",
pathname: "/books/123",
}),
);
console.log(
pattern.test({
protocol: "file",
hostname: "store.example.com",
pathname: "/books/123",
}),
);