Spec-Zone.ru › Deno 2

URL

Manipulate URLs, extract data from URLs and manage query parameters.

Eg URL


interface URL

The URL interface represents an object providing static methods used for creating, parsing, and manipulating URLs in Deno.

Use the URL API for safely parsing, constructing, normalizing, and encoding URLs. This is the preferred way to work with URLs in Deno rather than manual string manipulation which can lead to errors and security issues.

Properties

hash: string

The hash property of the URL interface is a string that starts with a # and is followed by the fragment identifier of the URL. It returns an empty string if the URL does not contain a fragment identifier.

host: string

The host property of the URL interface is a string that includes the URL.hostname and the URL.port if one is specified in the URL includes by including a : followed by the port number.

hostname: string

The hostname property of the URL interface is a string that represents the fully qualified domain name of the URL.

href: string

The href property of the URL interface is a string that represents the complete URL.

origin: string
readonly

The origin property of the URL interface is a string that represents the origin of the URL, that is the URL.protocol, URL.host, and URL.port.

password: string

The password property of the URL interface is a string that represents the password specified in the URL.

pathname: string

The pathname property of the URL interface is a string that represents the path of the URL.

port: string

The port property of the URL interface is a string that represents the port of the URL if an explicit port has been specified in the URL.

protocol: string

The protocol property of the URL interface is a string that represents the protocol scheme of the URL and includes a trailing :.

search: string

The search property of the URL interface is a string that represents the search string, or the query string, of the URL. This includes the ? character and the but excludes identifiers within the represented resource such as the URL.hash. More granular control can be found using URL.searchParams property.

searchParams: URLSearchParams
readonly

The searchParams property of the URL interface provides a direct interface to query parameters through a URLSearchParams object.

This property offers a convenient way to:

  • Parse URL query parameters
  • Manipulate query strings
  • Add, modify, or delete URL parameters
  • Work with form data in a URL-encoded format
  • Handle query string encoding/decoding automatically
username: string

The username property of the URL interface is a string that represents the username of the URL.

Methods

toString(): string

The toString() method of the URL interface returns a string containing the complete URL.

toJSON(): string

The toJSON() method of the URL interface returns a JSON representation of the URL.

See

  • https://developer.mozilla.org/docs/Web/API/URL

variable URL

The URL interface represents an object providing static methods used for creating, parsing, and manipulating URLs.

Properties

prototype: URL
readonly

Methods

parse(
url: string | URL,
base?: string | URL,
): URL | null

Parses a URL string or URL object and returns a URL object.

canParse(
url: string | URL,
base?: string | URL,
): boolean

Returns a boolean value indicating if a URL string is valid and can be parsed.

createObjectURL(blob: Blob): string

Creates a unique, temporary URL that represents a given Blob, File, or MediaSource object.

This method is particularly useful for:

  • Creating URLs for dynamically generated content
  • Working with blobs in a browser context
  • Creating workers from dynamically generated code
  • Setting up temporary URL references for file downloads

Note: Always call URL.revokeObjectURL() when you're done using the URL to prevent memory leaks.

revokeObjectURL(url: string): void

Revokes a previously created object URL, freeing the memory associated with it.

Important for memory management in applications that create dynamic URLs. Once an object URL is revoked:

  • It can no longer be used to fetch the content it referenced
  • The browser/runtime is allowed to release the memory or resources associated with it
  • Workers created via the URL will continue to run, but the URL becomes invalid for new creations

For security and performance in Deno applications, always revoke object URLs as soon as they're no longer needed, especially when processing large files or generating many URLs.

See

  • https://developer.mozilla.org/docs/Web/API/URL


interface URLPattern

The URLPattern API provides a web platform primitive for matching URLs based on a convenient pattern syntax.

Common use cases for URLPattern include:

  • Building routers for web applications
  • Pattern-matching URLs for middleware
  • Extracting parameters from URL paths
  • URL-based feature toggles
  • Routing in serverless and edge functions

The syntax is based on path-to-regexp, supporting wildcards, named capture groups, regular groups, and group modifiers - similar to Express.js route patterns.

Examples

// Basic routing with URLPattern (similar to Express.js)
const routes = [
  new URLPattern({ pathname: "/users" }),
  new URLPattern({ pathname: "/users/:id" }),
  new URLPattern({ pathname: "/products/:category/:id?" }),
];

// Check incoming request against routes
function handleRequest(req: Request) {
  const url = new URL(req.url);

  for (const route of routes) {
    const match = route.exec(url);
    if (match) {
      // Extract parameters from the URL
      const params = match.pathname.groups;
      return new Response(`Matched: ${JSON.stringify(params)}`);
    }
  }

  return new Response("Not found", { status: 404 });
}
// Matching different URL parts
const apiPattern = new URLPattern({
  protocol: "https",
  hostname: "api.example.com",
  pathname: "/v:version/:resource/:id?",
  search: "*", // Match any query string
});

const match = apiPattern.exec("https://api.example.com/v1/users/123?format=json");
if (match) {
  console.log(match.pathname.groups.version); // "1"
  console.log(match.pathname.groups.resource); // "users"
  console.log(match.pathname.groups.id); // "123"
}

Properties

protocol: string
readonly

The pattern string for the protocol.

username: string
readonly

The pattern string for the username.

password: string
readonly

The pattern string for the password.

hostname: string
readonly

The pattern string for the hostname.

port: string
readonly

The pattern string for the port.

pathname: string
readonly

The pattern string for the pathname.

search: string
readonly

The pattern string for the search.

hash: string
readonly

The pattern string for the hash.

hasRegExpGroups: boolean
readonly

Whether or not any of the specified groups use regexp groups.

Methods

test(
input: URLPatternInput,
baseURL?: string,
): boolean

Test if the given input matches the stored pattern.

The input can either be provided as an absolute URL string with an optional base, relative URL string with a required base, or as individual components in the form of an URLPatternInit object.

const pattern = new URLPattern("https://example.com/books/:id");

// Test an absolute url string.
console.log(pattern.test("https://example.com/books/123")); // true

// Test a relative url with a base.
console.log(pattern.test("/books/123", "https://example.com")); // true

// Test an object of url components.
console.log(pattern.test({ pathname: "/books/123" })); // true
exec(
input: URLPatternInput,
baseURL?: string,
): URLPatternResult | null

Match the given input against the stored pattern.

The input can either be provided as an absolute URL string with an optional base, relative URL string with a required base, or as individual components in the form of an URLPatternInit object.

const pattern = new URLPattern("https://example.com/books/:id");

// Match an absolute url string.
let match = pattern.exec("https://example.com/books/123");
console.log(match.pathname.groups.id); // 123

// Match a relative url with a base.
match = pattern.exec("/books/123", "https://example.com");
console.log(match.pathname.groups.id); // 123

// Match an object of url components.
match = pattern.exec({ pathname: "/books/123" });
console.log(match.pathname.groups.id); // 123

variable URLPattern

The URLPattern API provides a web platform primitive for matching URLs based on a convenient pattern syntax.

The syntax is based on path-to-regexp. Wildcards, named capture groups, regular groups, and group modifiers are all supported.

// Specify the pattern as structured data.
const pattern = new URLPattern({ pathname: "/users/:user" });
const match = pattern.exec("https://blog.example.com/users/joe");
console.log(match.pathname.groups.user); // joe
// Specify a fully qualified string pattern.
const pattern = new URLPattern("https://example.com/books/:id");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://deno.land/books/123")); // false
// Specify a relative string pattern with a base URL.
const pattern = new URLPattern("/article/:id", "https://blog.example.com");
console.log(pattern.test("https://blog.example.com/article")); // false
console.log(pattern.test("https://blog.example.com/article/123")); // true

Properties

prototype: URLPattern
readonly

interface URLPatternComponentResult

Properties

input: string
groups: Record<string, string | undefined>

interface URLPatternInit

Properties

protocol: string
optional
username: string
optional
password: string
optional
hostname: string
optional
port: string
optional
pathname: string
optional
search: string
optional
hash: string
optional
baseURL: string
optional

interface URLPatternOptions

Options for the URLPattern constructor.

Properties

ignoreCase: boolean = false

Enables case-insensitive matching.


interface URLPatternResult

URLPatternResult is the object returned from URLPattern.exec.

Properties

inputs: [URLPatternInit] | [URLPatternInit, string]

The inputs provided when matching.

protocol: URLPatternComponentResult

The matched result for the protocol matcher.

username: URLPatternComponentResult

The matched result for the username matcher.

password: URLPatternComponentResult

The matched result for the password matcher.

hostname: URLPatternComponentResult

The matched result for the hostname matcher.

port: URLPatternComponentResult

The matched result for the port matcher.

pathname: URLPatternComponentResult

The matched result for the pathname matcher.

search: URLPatternComponentResult

The matched result for the search matcher.

hash: URLPatternComponentResult

The matched result for the hash matcher.


interface URLSearchParams

URLSearchParams provides methods for working with the query string of a URL.

Use this interface to:

  • Parse query parameters from URLs
  • Build and modify query strings
  • Handle form data (when used with FormData)
  • Safely encode/decode URL parameter values

Properties

size: number
readonly

Contains the number of search parameters

searchParams.size

Methods

append(
name: string,
value: string,
): void

Appends a specified key/value pair as a new search parameter.

let searchParams = new URLSearchParams();
searchParams.append('name', 'first');
searchParams.append('name', 'second');
delete(
name: string,
value?: string,
): void

Deletes search parameters that match a name, and optional value, from the list of all search parameters.

let searchParams = new URLSearchParams([['name', 'value']]);
searchParams.delete('name');
searchParams.delete('name', 'value');
getAll(name: string): string[]

Returns all the values associated with a given search parameter as an array.

searchParams.getAll('name');
get(name: string): string | null

Returns the first value associated to the given search parameter.

searchParams.get('name');
has(
name: string,
value?: string,
): boolean

Returns a boolean value indicating if a given parameter, or parameter and value pair, exists.

searchParams.has('name');
searchParams.has('name', 'value');
set(
name: string,
value: string,
): void

Sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.

searchParams.set('name', 'value');
sort(): void

Sort all key/value pairs contained in this object in place and return undefined. The sort order is according to Unicode code points of the keys.

searchParams.sort();
forEach(
callbackfn: (
value: string,
key: string,
parent: this,
) => void
,
thisArg?: any,
): void

Calls a function for each element contained in this object in place and return undefined. Optionally accepts an object to use as this when executing callback as second argument.

const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
params.forEach((value, key, parent) => {
  console.log(value, key, parent);
});
keys(): URLSearchParamsIterator<string>

Returns an iterator allowing to go through all keys contained in this object.

const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const key of params.keys()) {
  console.log(key);
}
values(): URLSearchParamsIterator<string>

Returns an iterator allowing to go through all values contained in this object.

const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const value of params.values()) {
  console.log(value);
}
entries(): URLSearchParamsIterator<[string, string]>

Returns an iterator allowing to go through all key/value pairs contained in this object.

const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const [key, value] of params.entries()) {
  console.log(key, value);
}
[[Symbol.iterator]](): URLSearchParamsIterator<[string, string]>

Returns an iterator allowing to go through all key/value pairs contained in this object.

const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const [key, value] of params) {
  console.log(key, value);
}
toString(): string

Returns a query string suitable for use in a URL.

searchParams.toString();

variable URLSearchParams

The URLSearchParams interface defines utility methods to work with the query string of a URL. An object implementing URLSearchParams can directly be used in a for...of structure to iterate over key/value pairs in the same order as they appear in the query string.

Properties

prototype: URLSearchParams
readonly

See

  • https://developer.mozilla.org/docs/Web/API/URLSearchParams


interface URLSearchParamsIterator

extends IteratorObject<T, BuiltinIteratorReturn, unknown>

Iterator for the URLSearchParams class, used to iterate over key-value pairs in search parameters.

Examples

const url = new URL('https://example.org/path?a=1&b=2');
const queryString = url.search.substring(1); // Remove the leading '?'
const params = new URLSearchParams(queryString);
const iterator = params.entries();
console.log(iterator.next().value); // ['a', '1']
console.log(iterator.next().value); // ['b', '2']

Type Parameters

T

Methods

[[Symbol.iterator]](): URLSearchParamsIterator<T>

type alias URLPatternInput

Definition

string | URLPatternInit

© 2018–2025 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/api/web/url

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API