大网数据广告活动
Web 标准与前端开发

URLPattern: URLPattern() constructor

· 52CE 我爱测

The **`URLPattern()`** constructor returns a new URLPattern object representing the URLs that will be matched by this pattern.

URLPattern API

The URLPattern() constructor returns a new URLPattern object representing the URLs that will be matched by this pattern.

Syntax

new URLPattern(input)
new URLPattern(input, options)
new URLPattern(url)
new URLPattern(url, baseURL)
new URLPattern(url, baseURL, options)

Parameters

  • input

    • : An object that has separate properties for defining the patterns used to match each part of a URL.

      The object members can be any (or none) of:

      • protocol
        • : A pattern that matches a URL protocol, such as http, https, or "http{s}?" (to match both https and http).
      • username
        • : A pattern that matches a URL username.
      • password
        • : A pattern that matches a URL password.
      • hostname
        • : A pattern that matches a URL hostname.
      • port
        • : A pattern that matches a URL port.
      • pathname
        • : A pattern that matches a URL pathname.
      • search
        • : A pattern that matches a URL search.
      • hash
        • : A pattern that matches a URL hash.
      • baseURL
  • url

    • : A string representing URL patterns to match.

      This is formatted as an absolute or relative URL but may contain markup to indicate matching patterns and escape sequences. If formatted as a relative URL, then baseURL must also be provided.

  • baseURL

    • : A string that provides an absolute URL from which undefined less-specific URL-parts may be inherited This must be set when url is a relative URL, and must not be set if input is used (input.baseURL may be used to provide inherited values for an input, but, unlike this property, is never required).
  • options

    • : An object providing options for matching the given pattern. The allowed object members are:
      • ignoreCase
        • : Enables case-insensitive matching if set to true. If omitted or set to false, matching will be case-sensitive.

[!NOTE] All the URL parts in the input properties and the url are optional. If not specified in those parameters, some values may be inherited from the baseURL, depending on what other URL-parts are defined. Omitted parts are normalized to wildcards (*).

Exceptions

  • TypeError
    • : Indicates one of the following:
      • The given input, url or baseURL is not valid or syntactically correct.
      • The given url is relative, but no baseURL is provided to form a complete absolute URL.
      • A baseURL is provided, and input is an absolute pattern or a structured object.

Description

The URLPattern constructor can take either an "input" object or a URL string and optional baseURL. Both forms can also take an options object argument that sets additional matching options, such as case sensitivity.

new URLPattern(input);
new URLPattern(url, baseURL);

The input object used in the first type of constructor describes the URLs that should be matched by specifying patterns for individual URL parts: protocol, username, password, hostname, port, pathname, search, hash, and baseURL. If the baseURL property is provided it will be parsed as a URL and may be used to populate any other properties that are missing (see the following section Inheritance from a base URL). Properties that are omitted or not filled by the baseURL property default to the wildcard string (*), which match against any corresponding value in a URL.

The second type of constructor takes a URL string that may contain patterns embedded in it. The string may specify an absolute or relative URL — if the pattern is relative, then baseURL must be 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.

Inheritance from a BaseURL

URL-parts that are more specific than the least-specific part defined in the url may be inherited from baseURL (or from input.baseURL for input). Intuitively this means that if the pathname part is specified in the input, the parts to its left in a URL may be inherited from the base URL (protocol, hostname and port), while the parts to its right may not (search and hash). The username and password are never inherited from the base URL.

For more information see Inheritance from a BaseURL in the API overview.

Hostname in url or baseURL affects default port

Unlike other URL parts, the port may be implicitly set if you specify an url or base URL (either in the baseURL parameter or in the object) and don't explicitly specify a port. In this case the port will be set to the empty string ("") and match the default port (443).

For example, these patterns all set the port pattern to "":

new URLPattern("https://example.com");
new URLPattern("https://example.com*");
new URLPattern("https://example.com/foo");
new URLPattern({
  pathname: "/foo/*",
  baseURL: "https://example.com",
});

If you don't specify the hostname in an url or baseURL, the port will default to the wildcard string (*):

new URLPattern({ pathname: "/foo/*" }); // Port omitted, defaults to '*'

Escaping special characters

The pattern syntax includes a number of characters that can occur naturally in URLs, such as:

  • ? indicates both an optional character or group in a pattern and the search part of a URL.
  • : indicates the start of a named group in a pattern and a separator for username and password, or a hostname and a port.

If you're constructing a URLPattern using the url string parameter these special characters are assumed to be part of the pattern syntax (if there is any ambiguity). If you are using the characters to represent parts of the URL then you will need to escape them, by preceding the characters with \\ (or avoid the problem by constructing URLPattern using the object syntax).

For example, the following pattern escapes the ? character, which makes this pattern match a search URL-part of "fred"

console.log(new URLPattern("https://example.com/*\\?fred"));

Similarly, the Match the username and password example below shows a case where the : separator needs to be escaped.

Examples

Default pattern

This code demonstrates that URL-parts that are not supplied in a URL or inherited from a base URL default to the wildcard value.

console.log(new URLPattern());
console.log(new URLPattern({}));
/*
{
  protocol: "*",
  username: "*",
  password: "*",
  hostname: "*",
  port: "*",
  pathname: "*",
  search: "*",
  hash: "*",
  hasRegExpGroups: false,
};
*/

Matching a pathname

let pattern1 = new URLPattern("https://example.com/books/:id");

// same as
let pattern2 = new URLPattern("/books/:id", "https://example.com");

// or
let pattern3 = new URLPattern({
  protocol: "https",
  hostname: "example.com",
  pathname: "/books/:id",
});

// or
let pattern4 = new URLPattern({
  pathname: "/books/:id",
  baseURL: "https://example.com",
});

// or
let pattern5 = new URLPattern({
  pathname: "/books/:id",
  baseURL: "https://example.com/some/path/?search=3#param=1",
  // More-specific URL parts are discarded
});

Match the protocol and hostname

let pattern = new URLPattern({
  protocol: "http{s}?",
  hostname: ":subdomain.example.com",
});

Match the username and password

This sets the username and password URL parts using the pattern string. Note how the : separator needs to be escaped when using the pattern string. Without this the username pattern would be myusername:mypassword.

const pattern = new URLPattern(
  "https://myusername\\:mypassword@example.com/some/path",
);

console.log(pattern.username); // "myusername"
console.log(pattern.password); // "mypassword"

For this reason it is often more natural (and safer) to use the object syntax.

Match all possible structured parts

let pattern = new URLPattern({
  protocol: "http{s}?",
  username: ":username",
  password: ":password",
  hostname: ":subdomain.example.com",
  port: ":port(80|443)",
  pathname: "/:path",
  search: "*",
  hash: "*",
});

Case-insensitive matching

// Case-sensitive matching by default
const pattern = new URLPattern("https://example.com/2022/feb/*");
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // false

Setting the ignoreCase option to true in the constructor switches all matching operations to case-insensitive for the given pattern:

// Case-insensitive matching
const pattern = new URLPattern("https://example.com/2022/feb/*", {
  ignoreCase: true,
});
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // true

Inheritance from the base URL

This provides a real-world example of inheritance. The pathname is explicitly specified. The values that are less specific than the pathname, such as the protocol and hostname are inherited. The more specific values are ignored, and default to their default values (such as "*" for the search and hash, and "" for the port).

const pattern = new URLPattern({
  pathname: "/some/path",
  baseURL: "https://myuser:mypass@example.com/mypath?search=1&p=3#fred",
});

console.log(pattern);
// protocol: https
// username: *
// password: *
// hostname: example.com
// port:
// pathname: /some/path
// search: *
// hash: *

Specifications

Browser compatibility

See also

  • A polyfill of URLPattern is available on GitHub

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。