URLPattern.test()
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.
Note: This feature is available in Web Workers
Syntax
test(input); test(input, baseURL);
Parameters
input
-
The URL or URL parts to match against. This can either be a
USVString
, or an object providing the individual URL parts. The object members can be any ofprotocol
,username
,password
,hostname
,port
,pathname
,search
,hash
, orbaseURL
. Omitted parts in the object will be treated as empty strings. If the input cannot be parsed, or a relative URL without a base is provided, the method will returnnull
. -
baseURL
Optional -
A
USVString
representing the base URL to use in cases whereinput
is a relative URL. If not specified, it defaults toundefined
. If this parameter cannot be parsed, the method will returnfalse
.
Return value
A boolean
.
Examples
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'); // Absolute URL strings console.log(pattern.test('https://store.example.com/books/123')); // true console.log(pattern.test('https://example.com/books/123')); // false // Relative URL strings console.log(pattern.test('/books/123', 'http://store.example.com')); // true console.log(pattern.test('/books/123', 'data:text/plain,hello world!')); // false console.log(pattern.test('/books/123')); // false // Structured objects console.log(pattern.test({ pathname: '/books/123', baseURL: 'http://store.example.com', })); // true console.log(pattern.test({ protocol: 'https', hostname: 'store.example.com', pathname: '/books/123', })); // true console.log(pattern.test({ protocol: 'file', hostname: 'store.example.com', pathname: '/books/123', })); // false
Specifications
Specification |
---|
URLPattern API # dom-urlpattern-test |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
test |
95
93-95
|
95
93-95
|
No |
No |
81 |
No |
No |
95
93-95
|
No |
No |
No |
No |
See also
- A polyfill of
URLPattern
is available on GitHub
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/URLPattern/test