URL#

安定性: 2 - Stable

ソースコード: lib/url.js

node:url モジュールは、URL の解決と解析のためのユーティリティを提供します。これは以下のようにアクセスできます。

import url from 'node:url';const url = require('node:url');

URL 文字列と URL オブジェクト#

URL 文字列は、複数の意味のあるコンポーネントを含む構造化された文字列です。解析されると、これらの各コンポーネントのプロパティを含む URL オブジェクトが返されます。

node:url モジュールは URL を扱うための2つの API を提供します。1つは Node.js 固有のレガシー API、もう1つは Web ブラウザで使用されている WHATWG URL 標準と同じものを実装する新しい API です。

WHATWG API とレガシー API の比較を以下に示します。URL 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash' の上に、レガシー url.parse() によって返されるオブジェクトのプロパティが表示されています。その下には、WHATWG URL オブジェクトのプロパティがあります。

WHATWG URL の origin プロパティには protocolhost が含まれますが、usernamepassword は含まれません。

┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                              href                                              │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │  │        auth         │          host          │           path            │ hash  │
│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
│          │  │                     │    hostname     │ port │ pathname │     search     │       │
│          │  │                     │                 │      │          ├─┬──────────────┤       │
│          │  │                     │                 │      │          │ │    query     │       │
"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
│          │  │          │          │    hostname     │ port │          │                │       │
│          │  │          │          ├─────────────────┴──────┤          │                │       │
│ protocol │  │ username │ password │          host          │          │                │       │
├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
│   origin    │                     │         origin         │ pathname │     search     │ hash  │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│                                              href                                              │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
(All spaces in the "" line should be ignored. They are purely for formatting.) 

WHATWG API を使用して URL 文字列を解析する

const myURL =
  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'); 

レガシー API を使用して URL 文字列を解析する

import url from 'node:url';
const myURL =
  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');const url = require('node:url');
const myURL =
  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');

構成要素から URL を構築し、構築された文字列を取得する#

プロパティセッターまたはテンプレートリテラル文字列を使用して、構成要素から WHATWG URL を構築することが可能です。

const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh'; 
const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
const myURL = new URL(`https://example.org${pathname}${search}${hash}`); 

構築された URL 文字列を取得するには、href プロパティアクセサーを使用します。

console.log(myURL.href); 

WHATWG URL API#

クラス: URL#

WHATWG URL 標準に従って実装された、ブラウザ互換の URL クラスです。 解析された URL の例は標準自体にあります。URL クラスはグローバルオブジェクトでも利用可能です。

ブラウザの慣例に従い、URL オブジェクトのすべてのプロパティは、オブジェクト自体のデータプロパティとしてではなく、クラスプロトタイプのゲッターおよびセッターとして実装されています。したがって、レガシー urlObject とは異なり、URL オブジェクトのプロパティに対して delete キーワードを使用しても(例: delete myURL.protocoldelete myURL.pathname など)、何の効果もありませんが、true を返します。

new URL(input[, base])#
  • input <string> 解析する絶対または相対入力 URL。input が相対的な場合、base が必要です。input が絶対的な場合、base は無視されます。input が文字列でない場合、最初に文字列に変換されます
  • base <string> input が絶対でない場合に解決するためのベース URL。base が文字列でない場合、最初に文字列に変換されます

base を基準に input を解析して新しい URL オブジェクトを作成します。base が文字列として渡された場合、new URL(base) と同等に解析されます。

const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo 

URL コンストラクタはグローバルオブジェクトのプロパティとしてアクセス可能です。また、組み込みの url モジュールからインポートすることもできます。

import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.console.log(URL === require('node:url').URL); // Prints 'true'.

input または base が有効な URL でない場合、TypeError がスローされます。与えられた値は文字列に強制変換されることに注意してください。例えば、

const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/ 

input のホスト名内に現れる Unicode 文字は、Punycode アルゴリズムを使用して自動的に ASCII に変換されます。

const myURL = new URL('https://測試');
// https://xn--g6w251d/ 

input が絶対 URL かどうかが事前に分からず、base が提供されている場合、URL オブジェクトの origin が期待されるものであるか検証することをお勧めします。

let myURL = new URL('http://Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https://Example.com/', 'https://example.org/');
// https://example.com/

myURL = new URL('foo://Example.com/', 'https://example.org/');
// foo://Example.com/

myURL = new URL('http:Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https:Example.com/', 'https://example.org/');
// https://example.org/Example.com/

myURL = new URL('foo:Example.com/', 'https://example.org/');
// foo:Example.com/ 
url.hash#

URL のフラグメント部分を取得および設定します。

const myURL = new URL('https://example.org/foo#bar');
console.log(myURL.hash);
// Prints #bar

myURL.hash = 'baz';
console.log(myURL.href);
// Prints https://example.org/foo#baz 

hash プロパティに割り当てられた値に含まれる無効な URL 文字は、パーセントエンコードされます。どの文字をパーセントエンコードするかは、url.parse()url.format() メソッドが生成するものとは多少異なる場合があります。

url.host#

URL のホスト部分を取得および設定します。

const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);
// Prints example.org:81

myURL.host = 'example.com:82';
console.log(myURL.href);
// Prints https://example.com:82/foo 

host プロパティに割り当てられた無効なホスト値は無視されます。

url.hostname#

URL のホスト名部分を取得および設定します。url.hosturl.hostname の主な違いは、url.hostname にはポートが含まれないことです。

const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
// Prints example.org

// Setting the hostname does not change the port
myURL.hostname = 'example.com';
console.log(myURL.href);
// Prints https://example.com:81/foo

// Use myURL.host to change the hostname and port
myURL.host = 'example.org:82';
console.log(myURL.href);
// Prints https://example.org:82/foo 

hostname プロパティに割り当てられた無効なホスト名値は無視されます。

url.href#

シリアライズされた URL を取得および設定します。

const myURL = new URL('https://example.org/foo');
console.log(myURL.href);
// Prints https://example.org/foo

myURL.href = 'https://example.com/bar';
console.log(myURL.href);
// Prints https://example.com/bar 

href プロパティの値を取得することは、url.toString() を呼び出すことと同等です。

このプロパティの値を新しい値に設定することは、new URL(value) を使用して新しい URL オブジェクトを作成することと同等です。URL オブジェクトの各プロパティが変更されます。

href プロパティに割り当てられた値が有効な URL でない場合、TypeError がスローされます。

url.origin#

URL のオリジンの読み取り専用のシリアライズを取得します。

const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org 
const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d

console.log(idnURL.hostname);
// Prints xn--g6w251d 
url.password#

URL のパスワード部分を取得および設定します。

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);
// Prints xyz

myURL.password = '123';
console.log(myURL.href);
// Prints https://abc:123@example.com/ 

password プロパティに割り当てられた値に含まれる無効な URL 文字は、パーセントエンコードされます。どの文字をパーセントエンコードするかは、url.parse()url.format() メソッドが生成するものとは多少異なる場合があります。

url.pathname#

URL のパス部分を取得および設定します。

const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz

myURL.pathname = '/abcdef';
console.log(myURL.href);
// Prints https://example.org/abcdef?123 

pathname プロパティに割り当てられた値に含まれる無効な URL 文字は、パーセントエンコードされます。どの文字をパーセントエンコードするかは、url.parse()url.format() メソッドが生成するものとは多少異なる場合があります。

url.port#

URL のポート部分を取得および設定します。

ポート値は、0 から 65535(両端を含む)の範囲の数値または数値を含む文字列にすることができます。値を URL オブジェクトの指定された protocol のデフォルトポートに設定すると、port の値は空文字列 ('') になります。

ポート値は空文字列にすることができ、その場合ポートはプロトコル/スキームに依存します。

プロトコルポート
"ftp"21
"file"
"http"80
"https"443
"ws"80
"wss"443

ポートに値を割り当てると、値はまず .toString() を使用して文字列に変換されます。

その文字列が無効であっても数値で始まる場合、先頭の数値が port に割り当てられます。数値が上記の範囲外にある場合、それは無視されます。

const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// Prints 8888

// Default ports are automatically transformed to the empty string
// (HTTPS protocol's default port is 443)
myURL.port = '443';
console.log(myURL.port);
// Prints the empty string
console.log(myURL.href);
// Prints https://example.org/

myURL.port = 1234;
console.log(myURL.port);
// Prints 1234
console.log(myURL.href);
// Prints https://example.org:1234/

// Completely invalid port strings are ignored
myURL.port = 'abcd';
console.log(myURL.port);
// Prints 1234

// Leading numbers are treated as a port number
myURL.port = '5678abcd';
console.log(myURL.port);
// Prints 5678

// Non-integers are truncated
myURL.port = 1234.5678;
console.log(myURL.port);
// Prints 1234

// Out-of-range numbers which are not represented in scientific notation
// will be ignored.
myURL.port = 1e10; // 10000000000, will be range-checked as described below
console.log(myURL.port);
// Prints 1234 

浮動小数点数や科学表記の数値など、小数点を含む数値もこの規則の例外ではありません。小数点までの先頭の数値は、有効であれば URL のポートとして設定されます。

myURL.port = 4.567e21;
console.log(myURL.port);
// Prints 4 (because it is the leading number in the string '4.567e21') 
url.protocol#

URL のプロトコル部分を取得および設定します。

const myURL = new URL('https://example.org');
console.log(myURL.protocol);
// Prints https:

myURL.protocol = 'ftp';
console.log(myURL.href);
// Prints ftp://example.org/ 

protocol プロパティに割り当てられた無効な URL プロトコル値は無視されます。

特殊なスキーム#

WHATWG URL 標準は、いくつかの URL プロトコルスキームを、それらがどのように解析されシリアライズされるかという点で特殊であると見なします。これらの特殊なプロトコルのいずれかを使用して URL が解析されると、url.protocol プロパティは別の特殊なプロトコルに変更できますが、非特殊なプロトコルには変更できず、その逆も同様です。

例えば、http から https への変更は機能します。

const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org/ 

しかし、新しいプロトコルが特殊ではないため、http から仮説上の fish プロトコルへの変更は機能しません。

const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org/ 

同様に、非特殊なプロトコルから特殊なプロトコルへの変更も許可されていません。

const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org 

WHATWG URL 標準によると、特殊なプロトコルスキームは ftpfilehttphttpsws、および wss です。

url.search#

URL のシリアライズされたクエリ部分を取得および設定します。

const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
// Prints ?123

myURL.search = 'abc=xyz';
console.log(myURL.href);
// Prints https://example.org/abc?abc=xyz 

search プロパティに割り当てられた値に現れる無効な URL 文字は、パーセントエンコードされます。どの文字をパーセントエンコードするかは、url.parse()url.format() メソッドが生成するものとは多少異なる場合があります。

url.searchParams#

URL のクエリパラメータを表す URLSearchParams オブジェクトを取得します。このプロパティは読み取り専用ですが、提供される URLSearchParams オブジェクトを使用して URL インスタンスを変更できます。URL のクエリパラメータ全体を置き換えるには、url.search セッターを使用します。詳細は URLSearchParams のドキュメントを参照してください。

WHATWG 仕様によれば、URLSearchParams オブジェクトはどの文字をパーセントエンコードするかを決定するために異なるルールを使用するため、.searchParams を使用して URL を変更する際には注意が必要です。例えば、URL オブジェクトは ASCII チルダ (~) 文字をパーセントエンコードしませんが、URLSearchParams は常にエンコードします。

const myURL = new URL('https://example.org/abc?foo=~bar');

console.log(myURL.search);  // prints ?foo=~bar

// Modify the URL via searchParams...
myURL.searchParams.sort();

console.log(myURL.search);  // prints ?foo=%7Ebar 
url.username#

URL のユーザー名部分を取得および設定します。

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
// Prints abc

myURL.username = '123';
console.log(myURL.href);
// Prints https://123:xyz@example.com/ 

username プロパティに割り当てられた値に現れる無効な URL 文字は、パーセントエンコードされます。どの文字をパーセントエンコードするかは、url.parse()url.format() メソッドが生成するものとは多少異なる場合があります。

url.toString()#

URL オブジェクトの toString() メソッドは、シリアライズされた URL を返します。返される値は、url.href および url.toJSON() の値と同等です。

url.toJSON()#

URL オブジェクトの toJSON() メソッドは、シリアライズされた URL を返します。返される値は、url.href および url.toString() の値と同等です。

このメソッドは、URL オブジェクトが JSON.stringify() でシリアライズされるときに自動的に呼び出されます。

const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org'),
];
console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"] 
URL.createObjectURL(blob)#

与えられた <Blob> オブジェクトを表す 'blob:nodedata:...' URL 文字列を作成し、後でその Blob を取得するために使用できます。

const {
  Blob,
  resolveObjectURL,
} = require('node:buffer');

const blob = new Blob(['hello']);
const id = URL.createObjectURL(blob);

// later...

const otherBlob = resolveObjectURL(id);
console.log(otherBlob.size); 

登録された <Blob> によって格納されたデータは、URL.revokeObjectURL() が呼び出されて削除されるまでメモリに保持されます。

Blob オブジェクトは現在のスレッド内に登録されます。Worker Threads を使用している場合、1つの Worker 内で登録された Blob オブジェクトは他のワーカーやメインスレッドからは利用できません。

URL.revokeObjectURL(id)#
  • id <string> 事前に URL.createObjectURL() を呼び出して返された 'blob:nodedata:... URL 文字列。

指定された ID で識別される格納された <Blob> を削除します。登録されていない ID を取り消そうとすると、黙って失敗します。

URL.canParse(input[, base])#
  • input <string> 解析する絶対または相対入力 URL。input が相対的な場合、base が必要です。input が絶対的な場合、base は無視されます。input が文字列でない場合、最初に文字列に変換されます
  • base <string> input が絶対でない場合に解決するためのベース URL。base が文字列でない場合、最初に文字列に変換されます
  • 戻り値: <boolean>

base を基準にした inputURL に解析できるかどうかをチェックします。

const isValid = URL.canParse('/foo', 'https://example.org/'); // true

const isNotValid = URL.canParse('/foo'); // false 
URL.parse(input[, base])#
  • input <string> 解析する絶対または相対入力 URL。input が相対的な場合、base が必要です。input が絶対的な場合、base は無視されます。input が文字列でない場合、最初に文字列に変換されます
  • base <string> input が絶対でない場合に解決するためのベース URL。base が文字列でない場合、最初に文字列に変換されます
  • 戻り値: <URL> | <null>

文字列を URL として解析します。base が提供されている場合、それは非絶対的な input URL を解決する目的でベース URL として使用されます。パラメータが有効な URL に解決できない場合は null を返します。

クラス: URLPattern#

安定性: 1 - Experimental

URLPattern API は、URL または URL の一部をパターンと照合するためのインターフェースを提供します。

const myPattern = new URLPattern('https://node.dokyumento.jp/docs/latest/api/*.html');
console.log(myPattern.exec('https://node.dokyumento.jp/docs/latest/api/dns.html'));
// Prints:
// {
//  "hash": { "groups": {  "0": "" },  "input": "" },
//  "hostname": { "groups": {}, "input": "nodejs.org" },
//  "inputs": [
//    "https://node.dokyumento.jp/docs/latest/api/dns.html"
//  ],
//  "password": { "groups": { "0": "" }, "input": "" },
//  "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },
//  "port": { "groups": {}, "input": "" },
//  "protocol": { "groups": {}, "input": "https" },
//  "search": { "groups": { "0": "" }, "input": "" },
//  "username": { "groups": { "0": "" }, "input": "" }
// }

console.log(myPattern.test('https://node.dokyumento.jp/docs/latest/api/dns.html'));
// Prints: true 
new URLPattern()#

新しい空の URLPattern オブジェクトをインスタンス化します。

new URLPattern(string[, baseURL][, options])#

string を URL として解析し、それを使用して新しい URLPattern オブジェクトをインスタンス化します。

baseURL が指定されていない場合、デフォルトは undefined です。

オプションには、true に設定すると大文字と小文字を区別しないマッチングを有効にする ignoreCase ブール属性を持たせることができます。

コンストラクタは解析の失敗を示すために TypeError をスローすることがあります。

new URLPattern(obj[, baseURL][, options])#

Object を入力パターンとして解析し、それを使用して新しい URLPattern オブジェクトをインスタンス化します。オブジェクトのメンバーは protocolusernamepasswordhostnameportpathnamesearchhash、または baseURL のいずれかです。

baseURL が指定されていない場合、デフォルトは undefined です。

オプションには、true に設定すると大文字と小文字を区別しないマッチングを有効にする ignoreCase ブール属性を持たせることができます。

コンストラクタは解析の失敗を示すために TypeError をスローすることがあります。

urlPattern.exec(input[, baseURL])#

入力は、文字列または個々の URL 部分を提供するオブジェクトにすることができます。オブジェクトのメンバーは、protocolusernamepasswordhostnameportpathnamesearchhash、または baseURL のいずれかです。

baseURL が指定されていない場合、デフォルトは undefined になります。

関数に渡された引数の配列を含む inputs キーと、マッチした入力とマッチしたグループを含む URL コンポーネントのキーを持つオブジェクトを返します。

const myPattern = new URLPattern('https://node.dokyumento.jp/docs/latest/api/*.html');
console.log(myPattern.exec('https://node.dokyumento.jp/docs/latest/api/dns.html'));
// Prints:
// {
//  "hash": { "groups": {  "0": "" },  "input": "" },
//  "hostname": { "groups": {}, "input": "nodejs.org" },
//  "inputs": [
//    "https://node.dokyumento.jp/docs/latest/api/dns.html"
//  ],
//  "password": { "groups": { "0": "" }, "input": "" },
//  "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },
//  "port": { "groups": {}, "input": "" },
//  "protocol": { "groups": {}, "input": "https" },
//  "search": { "groups": { "0": "" }, "input": "" },
//  "username": { "groups": { "0": "" }, "input": "" }
// } 
urlPattern.test(input[, baseURL])#

入力は、文字列または個々の URL 部分を提供するオブジェクトにすることができます。オブジェクトのメンバーは、protocolusernamepasswordhostnameportpathnamesearchhash、または baseURL のいずれかです。

baseURL が指定されていない場合、デフォルトは undefined になります。

入力が現在のパターンに一致するかどうかを示すブール値を返します。

const myPattern = new URLPattern('https://node.dokyumento.jp/docs/latest/api/*.html');
console.log(myPattern.test('https://node.dokyumento.jp/docs/latest/api/dns.html'));
// Prints: true 

クラス: URLSearchParams#

URLSearchParams API は、URL のクエリへの読み書きアクセスを提供します。URLSearchParams クラスは、次の4つのコンストラクタのいずれかを使用してスタンドアロンで使用することもできます。URLSearchParams クラスはグローバルオブジェクトでも利用可能です。

WHATWG URLSearchParams インターフェースと querystring モジュールは似た目的を持っていますが、querystring モジュールの目的はより一般的であり、区切り文字(&=)のカスタマイズが可能です。一方、この API は純粋に URL クエリ文字列のために設計されています。

const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Prints 123

myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// Prints https://example.org/?abc=123&abc=xyz

myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// Prints https://example.org/?a=b

const newSearchParams = new URLSearchParams(myURL.searchParams);
// The above is equivalent to
// const newSearchParams = new URLSearchParams(myURL.search);

newSearchParams.append('a', 'c');
console.log(myURL.href);
// Prints https://example.org/?a=b
console.log(newSearchParams.toString());
// Prints a=b&a=c

// newSearchParams.toString() is implicitly called
myURL.search = newSearchParams;
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c 
new URLSearchParams()#

新しい空の URLSearchParams オブジェクトをインスタンス化します。

new URLSearchParams(string)#

string をクエリ文字列として解析し、それを使用して新しい URLSearchParams オブジェクトをインスタンス化します。先頭の '?' は、存在する場合は無視されます。

let params;

params = new URLSearchParams('user=abc&query=xyz');
console.log(params.get('user'));
// Prints 'abc'
console.log(params.toString());
// Prints 'user=abc&query=xyz'

params = new URLSearchParams('?user=abc&query=xyz');
console.log(params.toString());
// Prints 'user=abc&query=xyz' 
new URLSearchParams(obj)#
  • obj <Object> キーと値のペアのコレクションを表すオブジェクト

クエリハッシュマップで新しい URLSearchParams オブジェクトをインスタンス化します。obj の各プロパティのキーと値は常に文字列に強制変換されます。

querystring モジュールとは異なり、配列値の形式での重複キーは許可されません。配列は array.toString() を使用して文字列化されます。これは単にすべての配列要素をカンマで結合します。

const params = new URLSearchParams({
  user: 'abc',
  query: ['first', 'second'],
});
console.log(params.getAll('query'));
// Prints [ 'first,second' ]
console.log(params.toString());
// Prints 'user=abc&query=first%2Csecond' 
new URLSearchParams(iterable)#
  • iterable <Iterable> 要素がキーと値のペアであるイテラブルオブジェクト

<Map> のコンストラクタと同様の方法で、イテラブルマップを使用して新しい URLSearchParams オブジェクトをインスタンス化します。iterableArray または任意のイテラブルオブジェクトにすることができます。つまり、iterable は別の URLSearchParams であってもよく、その場合、コンストラクタは提供された URLSearchParams のクローンを単純に作成します。iterable の要素はキーと値のペアであり、それら自体も任意のイテラブルオブジェクトにすることができます。

重複キーは許可されます。

let params;

// Using an array
params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second'],
]);
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Using a Map object
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// Prints 'user=abc&query=xyz'

// Using a generator function
function* getQueryPairs() {
  yield ['user', 'abc'];
  yield ['query', 'first'];
  yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Each key-value pair must have exactly two elements
new URLSearchParams([
  ['user', 'abc', 'error'],
]);
// Throws TypeError [ERR_INVALID_TUPLE]:
//        Each query pair must be an iterable [name, value] tuple 
urlSearchParams.append(name, value)#

新しい名前と値のペアをクエリ文字列に追加します。

urlSearchParams.delete(name[, value])#

value が提供された場合、名前が name で値が value であるすべての名前と値のペアを削除します。

value が提供されない場合、名前が name であるすべての名前と値のペアを削除します。

urlSearchParams.entries()#

クエリ内の各名前と値のペアに対する ES6 Iterator を返します。イテレータの各項目は JavaScript の Array です。Array の最初の項目は name、2番目の項目は value です。

urlSearchParams[Symbol.iterator]() のエイリアスです。

urlSearchParams.forEach(fn[, thisArg])#
  • fn <Function> クエリ内の各名前と値のペアに対して呼び出されます
  • thisArg <Object> fn が呼び出されるときに this の値として使用されます

クエリ内の各名前と値のペアを反復処理し、指定された関数を呼び出します。

const myURL = new URL('https://example.org/?a=b&c=d');
myURL.searchParams.forEach((value, name, searchParams) => {
  console.log(name, value, myURL.searchParams === searchParams);
});
// Prints:
//   a b true
//   c d true 
urlSearchParams.get(name)#
  • name <string>
  • 戻り値: <string> | <null> 文字列、または指定された name を持つ名前と値のペアがない場合は null

名前が name である最初の名前と値のペアの値を返します。そのようなペアがない場合は null が返されます。

urlSearchParams.getAll(name)#

名前が name であるすべての名前と値のペアの値を返します。そのようなペアがない場合は、空の配列が返されます。

urlSearchParams.has(name[, value])#

URLSearchParams オブジェクトに name とオプションの value 引数に基づいてキーと値のペアが含まれているかどうかをチェックします。

value が指定された場合、同じ namevalue を持つ名前と値のペアが存在する場合に true を返します。

value が指定されていない場合、名前が name である名前と値のペアが少なくとも1つ存在する場合に true を返します。

urlSearchParams.keys()#

各名前と値のペアの名前に対する ES6 Iterator を返します。

const params = new URLSearchParams('foo=bar&foo=baz');
for (const name of params.keys()) {
  console.log(name);
}
// Prints:
//   foo
//   foo 
urlSearchParams.set(name, value)#

URLSearchParams オブジェクト内の name に関連付けられた値を value に設定します。名前が name である既存の名前と値のペアがある場合、最初のそのようなペアの値を value に設定し、その他すべてを削除します。ない場合は、名前と値のペアをクエリ文字列に追加します。

const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('foo', 'baz');
params.append('abc', 'def');
console.log(params.toString());
// Prints foo=bar&foo=baz&abc=def

params.set('foo', 'def');
params.set('xyz', 'opq');
console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq 
urlSearchParams.size#

パラメータエントリの総数。

urlSearchParams.sort()#

既存のすべての名前と値のペアを、その名前によってインプレースでソートします。ソートは安定ソートアルゴリズムで行われるため、同じ名前を持つ名前と値のペア間の相対的な順序は保持されます。

このメソッドは、特にキャッシュヒット率を向上させるために使用できます。

const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
params.sort();
console.log(params.toString());
// Prints query%5B%5D=abc&query%5B%5D=123&type=search 
urlSearchParams.toString()#

検索パラメータを文字列としてシリアライズして返します。必要に応じて文字はパーセントエンコードされます。

urlSearchParams.values()#

各名前と値のペアの値に対する ES6 Iterator を返します。

urlSearchParams[Symbol.iterator]()#

クエリ文字列内の各名前と値のペアに対する ES6 Iterator を返します。イテレータの各項目は JavaScript の Array です。Array の最初の項目は name、2番目の項目は value です。

urlSearchParams.entries() のエイリアスです。

const params = new URLSearchParams('foo=bar&xyz=baz');
for (const [name, value] of params) {
  console.log(name, value);
}
// Prints:
//   foo bar
//   xyz baz 

url.domainToASCII(domain)#

domainPunycode ASCII シリアライゼーションを返します。domain が無効なドメインの場合、空文字列が返されます。

これは url.domainToUnicode() の逆の操作を実行します。

import url from 'node:url';

console.log(url.domainToASCII('español.com'));
// Prints xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty stringconst url = require('node:url');

console.log(url.domainToASCII('español.com'));
// Prints xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string

url.domainToUnicode(domain)#

domain の Unicode シリアライゼーションを返します。domain が無効なドメインの場合、空文字列が返されます。

これは url.domainToASCII() の逆の操作を実行します。

import url from 'node:url';

console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// Prints español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty stringconst url = require('node:url');

console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// Prints español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string

url.fileURLToPath(url[, options])#

  • url <URL> | <string> パスに変換するファイル URL 文字列または URL オブジェクト。
  • options <Object>
    • windows <boolean> | <undefined> path を Windows のファイルパスとして返す場合は true、POSIX の場合は false、システムデフォルトの場合は undefinedデフォルト: undefined
  • 戻り値: <string> 完全に解決されたプラットフォーム固有の Node.js ファイルパス。

この関数は、パーセントエンコードされた文字の正しいデコードと、クロスプラットフォームで有効な絶対パス文字列を保証します。

import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);

new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');         // Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');       // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');         // Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname;   // Incorrect: /hello%20world
fileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)const { fileURLToPath } = require('node:url');
new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');         // Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');       // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');         // Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname;   // Incorrect: /hello%20world
fileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)

url.fileURLToPathBuffer(url[, options])#

  • url <URL> | <string> パスに変換するファイル URL 文字列または URL オブジェクト。
  • options <Object>
    • windows <boolean> | <undefined> path を Windows のファイルパスとして返す場合は true、POSIX の場合は false、システムデフォルトの場合は undefinedデフォルト: undefined
  • 戻り値: <Buffer> <Buffer> としての完全に解決されたプラットフォーム固有の Node.js ファイルパス。

url.fileURLToPath(...) と同様ですが、パスの文字列表現を返す代わりに Buffer が返されます。この変換は、入力 URL に有効な UTF-8 / Unicode シーケンスではないパーセントエンコードされたセグメントが含まれている場合に役立ちます。

url.format(URL[, options])#

  • URL <URL> WHATWG URL オブジェクト
  • options <Object>
    • auth <boolean> シリアライズされた URL 文字列にユーザー名とパスワードを含める場合は true、それ以外は falseデフォルト: true
    • fragment <boolean> シリアライズされた URL 文字列にフラグメントを含める場合は true、それ以外は falseデフォルト: true
    • search <boolean> シリアライズされた URL 文字列に検索クエリを含める場合は true、それ以外は falseデフォルト: true
    • unicode <boolean> URL 文字列のホストコンポーネントに現れる Unicode 文字を、Punycode エンコードするのではなく直接エンコードする場合は trueデフォルト: false
  • 戻り値: <string>

WHATWG URL オブジェクトの URL String 表現のカスタマイズ可能なシリアライゼーションを返します。

URL オブジェクトには、URL の文字列表現を返す toString() メソッドと href プロパティの両方があります。しかし、これらは一切カスタマイズできません。url.format(URL[, options]) メソッドは、出力の基本的なカスタマイズを可能にします。

import url from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'const url = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'

url.pathToFileURL(path[, options])#

  • path <string> ファイル URL に変換するパス。
  • options <Object>
    • windows <boolean> | <undefined> path を Windows のファイルパスとして扱う場合は true、POSIX の場合は false、システムデフォルトの場合は undefinedデフォルト: undefined
  • 戻り値: <URL> ファイル URL オブジェクト。

この関数は、path が絶対的に解決されること、およびファイル URL に変換する際に URL 制御文字が正しくエンコードされることを保証します。

import { pathToFileURL } from 'node:url';

new URL('/foo#1', 'file:');           // Incorrect: file:///foo#1
pathToFileURL('/foo#1');              // Correct:   file:///foo%231 (POSIX)

new URL('/some/path%.c', 'file:');    // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c');       // Correct:   file:///some/path%25.c (POSIX)const { pathToFileURL } = require('node:url');
new URL(__filename);                  // Incorrect: throws (POSIX)
new URL(__filename);                  // Incorrect: C:\... (Windows)
pathToFileURL(__filename);            // Correct:   file:///... (POSIX)
pathToFileURL(__filename);            // Correct:   file:///C:/... (Windows)

new URL('/foo#1', 'file:');           // Incorrect: file:///foo#1
pathToFileURL('/foo#1');              // Correct:   file:///foo%231 (POSIX)

new URL('/some/path%.c', 'file:');    // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c');       // Correct:   file:///some/path%25.c (POSIX)

url.urlToHttpOptions(url)#

  • url <URL> オプションオブジェクトに変換する WHATWG URL オブジェクト。
  • 戻り値: <Object> オプションオブジェクト
    • protocol <string> 使用するプロトコル。
    • hostname <string> リクエストを発行するサーバーのドメイン名または IP アドレス。
    • hash <string> URL のフラグメント部分。
    • search <string> URL のシリアライズされたクエリ部分。
    • pathname <string> URL のパス部分。
    • path <string> リクエストパス。クエリ文字列があれば含める必要があります。例: '/index.html?page=12'。リクエストパスに不正な文字が含まれている場合、例外がスローされます。現在、スペースのみが拒否されていますが、将来変更される可能性があります。
    • href <string> シリアライズされた URL。
    • port <number> リモートサーバーのポート。
    • auth <string> Authorization ヘッダーを計算するための基本認証、つまり 'user:password'

このユーティリティ関数は、URL オブジェクトを http.request() および https.request() API が期待する通常のオプションオブジェクトに変換します。

import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(urlToHttpOptions(myURL));
/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(urlToHttpOptions(myURL));
/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/

レガシー URL API#

安定性: 3 - レガシー: 代わりに WHATWG URL API を使用してください。

レガシー urlObject#

レガシー urlObject (require('node:url').Url または import { Url } from 'node:url') は url.parse() 関数によって作成され、返されます。

urlObject.auth#

auth プロパティは URL のユーザー名とパスワード部分であり、userinfo とも呼ばれます。この文字列サブセットは、protocol と二重スラッシュ(存在する場合)の後に続き、@ で区切られた host コンポーネントの前にあります。文字列はユーザー名、またはユーザー名とパスワードを : で区切ったものです。

例: 'user:pass'

urlObject.hash#

hash プロパティは、先頭の # 文字を含む URL のフラグメント識別子部分です。

例: '#hash'

urlObject.host#

host プロパティは、指定されている場合は port を含む、URL の完全な小文字のホスト部分です。

例: 'sub.example.com:8080'

urlObject.hostname#

hostname プロパティは、port を含まない host コンポーネントの小文字のホスト名部分です。

例: 'sub.example.com'

urlObject.href#

href プロパティは、protocolhost の両方のコンポーネントが小文字に変換された、解析された完全な URL 文字列です。

例: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'

urlObject.path#

path プロパティは、pathnamesearch コンポーネントの連結です。

例: '/p/a/t/h?query=string'

path のデコードは実行されません。

urlObject.pathname#

pathname プロパティは、URL のパスセクション全体で構成されます。これは、hostport を含む)の後ろで、ASCII の疑問符 (?) またはハッシュ (#) 文字で区切られた query または hash コンポーネントの開始前のすべてです。

例: '/p/a/t/h'

パス文字列のデコードは実行されません。

urlObject.port#

port プロパティは、host コンポーネントの数値ポート部分です。

例: '8080'

urlObject.protocol#

protocol プロパティは、URL の小文字のプロトコルスキームを識別します。

例: 'http:'

urlObject.query#

query プロパティは、先頭の ASCII 疑問符 (?) を除いたクエリ文字列、または querystring モジュールの parse() メソッドによって返されるオブジェクトのいずれかです。query プロパティが文字列かオブジェクトかは、url.parse() に渡される parseQueryString 引数によって決まります。

例: 'query=string' または {'query': 'string'}

文字列として返された場合、クエリ文字列のデコードは実行されません。オブジェクトとして返された場合、キーと値の両方がデコードされます。

urlObject.search#

search プロパティは、先頭の ASCII 疑問符 (?) 文字を含む、URL の「クエリ文字列」部分全体で構成されます。

例: '?query=string'

クエリ文字列のデコードは実行されません。

urlObject.slashes#

slashes プロパティは、protocol のコロンの後に2つの ASCII スラッシュ文字 (/) が必要な場合は true の値を持つ boolean です。

url.format(urlObject)#

  • urlObject <Object> | <string> URL オブジェクト (url.parse() によって返されるか、その他の方法で構築されたもの)。文字列の場合、url.parse() に渡すことによってオブジェクトに変換されます。

url.format() メソッドは、urlObject から派生したフォーマットされた URL 文字列を返します。

const url = require('node:url');
url.format({
  protocol: 'https',
  hostname: 'example.com',
  pathname: '/some/path',
  query: {
    page: 1,
    format: 'json',
  },
});

// => 'https://example.com/some/path?page=1&format=json' 

urlObject がオブジェクトでも文字列でもない場合、url.format()TypeError をスローします。

フォーマット処理は次のように動作します。

  • 新しい空の文字列 result が作成されます。
  • urlObject.protocol が文字列の場合、そのまま result に追加されます。
  • それ以外の場合、urlObject.protocolundefined でなく、文字列でもない場合、Error がスローされます。
  • ASCII コロン (:) 文字で終わらない urlObject.protocol のすべての文字列値に対して、リテラル文字列 :result に追加されます。
  • 次のいずれかの条件が真である場合、リテラル文字列 //result に追加されます。
    • urlObject.slashes プロパティが true です。
    • urlObject.protocolhttphttpsftpgopher、または file で始まります。
  • urlObject.auth プロパティの値が truthy で、かつ urlObject.host または urlObject.hostnameundefined でない場合、urlObject.auth の値は文字列に強制変換され、リテラル文字列 @ が続いて result に追加されます。
  • urlObject.host プロパティが undefined の場合:
    • urlObject.hostname が文字列の場合、それが result に追加されます。
    • それ以外の場合、urlObject.hostnameundefined でなく、文字列でもない場合、Error がスローされます。
    • urlObject.port プロパティの値が truthy で、かつ urlObject.hostnameundefined でない場合:
      • リテラル文字列 :result に追加され、
      • urlObject.port の値が文字列に強制変換され、result に追加されます。
  • それ以外の場合、urlObject.host プロパティの値が truthy であれば、urlObject.host の値が文字列に強制変換され、result に追加されます。
  • urlObject.pathname プロパティが空文字列ではない文字列の場合:
    • urlObject.pathname が ASCII スラッシュ (/) で始まらない場合、リテラル文字列 '/'result に追加されます。
    • urlObject.pathname の値が result に追加されます。
  • それ以外の場合、urlObject.pathnameundefined でなく、文字列でもない場合、Error がスローされます。
  • urlObject.search プロパティが undefined で、かつ urlObject.query プロパティが Object の場合、リテラル文字列 ?result に追加され、その後に querystring モジュールの stringify() メソッドを urlObject.query の値を渡して呼び出した出力が続きます。
  • それ以外の場合、urlObject.search が文字列の場合:
    • urlObject.search の値が ASCII 疑問符 (?) 文字で始まらない場合、リテラル文字列 ?result に追加されます。
    • urlObject.search の値が result に追加されます。
  • それ以外の場合、urlObject.searchundefined でなく、文字列でもない場合、Error がスローされます。
  • urlObject.hash プロパティが文字列の場合:
    • urlObject.hash の値が ASCII ハッシュ (#) 文字で始まらない場合、リテラル文字列 #result に追加されます。
    • urlObject.hash の値が result に追加されます。
  • それ以外の場合、urlObject.hash プロパティが undefined でなく、文字列でもない場合、Error がスローされます。
  • result が返されます。

url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#

安定性: 0 - 非推奨: 代わりに WHATWG URL API を使用してください。

  • urlString <string> 解析する URL 文字列。
  • parseQueryString <boolean> true の場合、query プロパティは常に querystring モジュールの parse() メソッドによって返されるオブジェクトに設定されます。false の場合、返される URL オブジェクトの query プロパティは解析されず、デコードされていない文字列になります。デフォルト: false
  • slashesDenoteHost <boolean> true の場合、リテラル文字列 // の後の最初のトークンと次の / の前が host として解釈されます。例えば、//foo/bar の場合、結果は {host: 'foo', pathname: '/bar'} となり、{pathname: '//foo/bar'} ではありません。デフォルト: false

url.parse() メソッドは URL 文字列を受け取り、それを解析し、URL オブジェクトを返します。

urlString が文字列でない場合、TypeError がスローされます。

auth プロパティが存在するがデコードできない場合、URIError がスローされます。

url.parse() は、URL 文字列を解析するために、寛容で非標準のアルゴリズムを使用します。これは、ホスト名のなりすましや、ユーザー名とパスワードの不適切な処理などのセキュリティ問題を起こしやすいです。信頼できない入力には使用しないでください。url.parse() の脆弱性に対して CVE は発行されません。代わりに WHATWG URL API を使用してください。例:

function getURL(req) {
  const proto = req.headers['x-forwarded-proto'] || 'https';
  const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com';
  return new URL(`${proto}://${host}${req.url || '/'}`);
} 

上記の例は、適切にフォーマットされたヘッダーがリバースプロキシから Node.js サーバーに転送されることを前提としています。リバースプロキシを使用していない場合は、以下の例を使用する必要があります。

function getURL(req) {
  return new URL(`https://example.com${req.url || '/'}`);
} 

url.resolve(from, to)#

  • from <string> to が相対 URL の場合に使用するベース URL。
  • to <string> 解決するターゲット URL。

url.resolve() メソッドは、Web ブラウザがアンカータグを解決するのと同様の方法で、ベース URL に対してターゲット URL を解決します。

const url = require('node:url');
url.resolve('/one/two/three', 'four');         // '/one/two/four'
url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' 

WHATWG URL API を使用して同じ結果を得るには:

function resolve(from, to) {
  const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
  if (resolvedUrl.protocol === 'resolve:') {
    // `from` is a relative URL.
    const { pathname, search, hash } = resolvedUrl;
    return pathname + search + hash;
  }
  return resolvedUrl.toString();
}

resolve('/one/two/three', 'four');         // '/one/two/four'
resolve('http://example.com/', '/one');    // 'http://example.com/one'
resolve('http://example.com/one', '/two'); // 'http://example.com/two' 

URL におけるパーセントエンコーディング#

URL には特定の範囲の文字しか含めることができません。その範囲外の文字はエンコードする必要があります。そのような文字がどのようにエンコードされるか、どの文字をエンコードするかは、その文字が URL の構造内のどこに位置するかに完全に依存します。

レガシー API#

レガシー API 内では、スペース (' ') と以下の文字は URL オブジェクトのプロパティで自動的にエスケープされます。

< > " ` \r \n \t { } | \ ^ ' 

例えば、ASCII スペース文字 (' ') は %20 としてエンコードされます。ASCII スラッシュ (/) 文字は %3C としてエンコードされます。

WHATWG API#

WHATWG URL 標準は、レガシー API で使用されるものよりも、エンコードされる文字を選択するために、より選択的で細分化されたアプローチを使用します。

WHATWG アルゴリズムは、パーセントエンコードされなければならない文字の範囲を記述する4つの「パーセントエンコードセット」を定義します。

  • C0 制御パーセントエンコードセットには、U+0000 から U+001F (両端を含む) の範囲のコードポイントと、U+007E (~) より大きいすべてのコードポイントが含まれます。

  • フラグメントパーセントエンコードセットには、C0 制御パーセントエンコードセットと、コードポイント U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), および U+0060 (`) が含まれます。

  • パスパーセントエンコードセットには、C0 制御パーセントエンコードセットと、コードポイント U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), U+003E (>), U+003F (?), U+0060 (`), U+007B ({), および U+007D (}) が含まれます。

  • ユーザー情報エンコードセットには、パスパーセントエンコードセットと、コードポイント U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), U+005B ([) から U+005E(^), および U+007C (|) が含まれます。

ユーザー情報パーセントエンコードセットは、URL 内にエンコードされたユーザー名とパスワード専用です。パスパーセントエンコードセットは、ほとんどの URL のパスに使用されます。フラグメントパーセントエンコードセットは、URL フラグメントに使用されます。C0 制御パーセントエンコードセットは、特定の条件下でホストとパスに使用され、その他すべての場合にも使用されます。

ホスト名内に非 ASCII 文字が現れる場合、ホスト名は Punycode アルゴリズムを使用してエンコードされます。ただし、ホスト名には Punycode エンコードされた文字とパーセントエンコードされた文字の両方が含まれる場合があることに注意してください。

const myURL = new URL('https://%CF%80.example.com/foo');
console.log(myURL.href);
// Prints https://xn--1xa.example.com/foo
console.log(myURL.origin);
// Prints https://xn--1xa.example.com