forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.md
More file actions
1112 lines (828 loc) · 37.2 KB
/
url.md
File metadata and controls
1112 lines (828 loc) · 37.2 KB
Edit and raw actions
OlderNewer
1
# URL
2
3
> Stability: 2 - Stable
4
5
The `url` module provides utilities for URL resolution and parsing. It can be
6
accessed using:
7
8
```js
9
const url = require('url');
10
```
11
12
## URL Strings and URL Objects
13
14
A URL string is a structured string containing multiple meaningful components.
15
When parsed, a URL object is returned containing properties for each of these
16
components.
17
18
The following details each of the components of a parsed URL. The example
19
`'http://user:[email protected]:8080/p/a/t/h?query=string#hash'` is used to
20
illustrate each.
21
22
```txt
23
┌─────────────────────────────────────────────────────────────────────────────────┐
24
│ href │
25
├──────────┬┬───────────┬─────────────────────┬───────────────────────────┬───────┤
26
│ protocol ││ auth │ host │ path │ hash │
27
│ ││ ├──────────────┬──────┼──────────┬────────────────┤ │
28
│ ││ │ hostname │ port │ pathname │ search │ │
29
│ ││ │ │ │ ├─┬──────────────┤ │
30
│ ││ │ │ │ │ │ query │ │
31
" http: // user:pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash "
32
│ ││ │ │ │ │ │ │ │
33
└──────────┴┴───────────┴──────────────┴──────┴──────────┴─┴──────────────┴───────┘
34
(all spaces in the "" line should be ignored -- they are purely for formatting)
35
```
36
37
### urlObject.auth
38
39
The `auth` property is the username and password portion of the URL, also
40
referred to as "userinfo". This string subset follows the `protocol` and
41
double slashes (if present) and precedes the `host` component, delimited by an
42
ASCII "at sign" (`@`). The format of the string is `{username}[:{password}]`,
43
with the `[:{password}]` portion being optional.
44
45
For example: `'user:pass'`
46
47
### urlObject.hash
48
49
The `hash` property consists of the "fragment" portion of the URL including
50
the leading ASCII hash (`#`) character.
51
52
For example: `'#hash'`
53
54
### urlObject.host
55
56
The `host` property is the full lower-cased host portion of the URL, including
57
the `port` if specified.
58
59
For example: `'host.com:8080'`
60
61
### urlObject.hostname
62
63
The `hostname` property is the lower-cased host name portion of the `host`
64
component *without* the `port` included.
65
66
For example: `'host.com'`
67
68
### urlObject.href
69
70
The `href` property is the full URL string that was parsed with both the
71
`protocol` and `host` components converted to lower-case.
72
73
For example: `'http://user:[email protected]:8080/p/a/t/h?query=string#hash'`
74
75
### urlObject.path
76
77
The `path` property is a concatenation of the `pathname` and `search`
78
components.
79
80
For example: `'/p/a/t/h?query=string'`
81
82
No decoding of the `path` is performed.
83
84
### urlObject.pathname
85
86
The `pathname` property consists of the entire path section of the URL. This
87
is everything following the `host` (including the `port`) and before the start
88
of the `query` or `hash` components, delimited by either the ASCII question
89
mark (`?`) or hash (`#`) characters.
90
91
For example `'/p/a/t/h'`
92
93
No decoding of the path string is performed.
94
95
### urlObject.port
96
97
The `port` property is the numeric port portion of the `host` component.
98
99
For example: `'8080'`
100
101
### urlObject.protocol
102
103
The `protocol` property identifies the URL's lower-cased protocol scheme.
104
105
For example: `'http:'`
106
107
### urlObject.query
108
109
The `query` property is either the query string without the leading ASCII
110
question mark (`?`), or an object returned by the [`querystring`][] module's
111
`parse()` method. Whether the `query` property is a string or object is
112
determined by the `parseQueryString` argument passed to `url.parse()`.
113
114
For example: `'query=string'` or `{'query': 'string'}`
115
116
If returned as a string, no decoding of the query string is performed. If
117
returned as an object, both keys and values are decoded.
118
119
### urlObject.search
120
121
The `search` property consists of the entire "query string" portion of the
122
URL, including the leading ASCII question mark (`?`) character.
123
124
For example: `'?query=string'`
125
126
No decoding of the query string is performed.
127
128
### urlObject.slashes
129
130
The `slashes` property is a `boolean` with a value of `true` if two ASCII
131
forward-slash characters (`/`) are required following the colon in the
132
`protocol`.
133
134
## url.format(urlObject)
135
<!-- YAML
136
added: v0.1.25
137
-->
138
139
* `urlObject` {Object|string} A URL object (as returned by `url.parse()` or
140
constructed otherwise). If a string, it is converted to an object by passing
141
it to `url.parse()`.
142
143
The `url.format()` method returns a formatted URL string derived from
144
`urlObject`.
145
146
If `urlObject` is not an object or a string, `url.parse()` will throw a
147
[`TypeError`][].
148
149
The formatting process operates as follows:
150
151
* A new empty string `result` is created.
152
* If `urlObject.protocol` is a string, it is appended as-is to `result`.
153
* Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an
154
[`Error`][] is thrown.
155
* For all string values of `urlObject.protocol` that *do not end* with an ASCII
156
colon (`:`) character, the literal string `:` will be appended to `result`.
157
* If either of the following conditions is true, then the literal string `//`
158
will be appended to `result`:
159
* `urlObject.slashes` property is true;
160
* `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or
161
`file`;
162
* If the value of the `urlObject.auth` property is truthy, and either
163
`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of
164
`urlObject.auth` will be coerced into a string and appended to `result`
165
followed by the literal string `@`.
166
* If the `urlObject.host` property is `undefined` then:
167
* If the `urlObject.hostname` is a string, it is appended to `result`.
168
* Otherwise, if `urlObject.hostname` is not `undefined` and is not a string,
169
an [`Error`][] is thrown.
170
* If the `urlObject.port` property value is truthy, and `urlObject.hostname`
171
is not `undefined`:
172
* The literal string `:` is appended to `result`, and
173
* The value of `urlObject.port` is coerced to a string and appended to
174
`result`.
175
* Otherwise, if the `urlObject.host` property value is truthy, the value of
176
`urlObject.host` is coerced to a string and appended to `result`.
177
* If the `urlObject.pathname` property is a string that is not an empty string:
178
* If the `urlObject.pathname` *does not start* with an ASCII forward slash
179
(`/`), then the literal string '/' is appended to `result`.
180
* The value of `urlObject.pathname` is appended to `result`.
181
* Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an
182
[`Error`][] is thrown.
183
* If the `urlObject.search` property is `undefined` and if the `urlObject.query`
184
property is an `Object`, the literal string `?` is appended to `result`
185
followed by the output of calling the [`querystring`][] module's `stringify()`
186
method passing the value of `urlObject.query`.
187
* Otherwise, if `urlObject.search` is a string:
188
* If the value of `urlObject.search` *does not start* with the ASCII question
189
mark (`?`) character, the literal string `?` is appended to `result`.
190
* The value of `urlObject.search` is appended to `result`.
191
* Otherwise, if `urlObject.search` is not `undefined` and is not a string, an
192
[`Error`][] is thrown.
193
* If the `urlObject.hash` property is a string:
194
* If the value of `urlObject.hash` *does not start* with the ASCII hash (`#`)
195
character, the literal string `#` is appended to `result`.
196
* The value of `urlObject.hash` is appended to `result`.
197
* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a
198
string, an [`Error`][] is thrown.
199
* `result` is returned.
200
201
## url.format(URL[, options])
202
203
> Stability: 1 - Experimental
204
205
* `URL` {URL} A [WHATWG URL][] object
206
* `options` {Object}
207
* `auth` {boolean} `true` if the serialized URL string should include the
208
username and password, `false` otherwise. Defaults to `true`.
209
* `fragment` {boolean} `true` if the serialized URL string should include the
210
fragment, `false` otherwise. Defaults to `true`.
211
* `search` {boolean} `true` if the serialized URL string should include the
212
search query, `false` otherwise. Defaults to `true`.
213
* `unicode` (Boolean) `true` if Unicode characters appearing in the host
214
component of the URL string should be encoded directly as opposed to being
215
Punycode encoded. Defaults to `false`.
216
217
Returns a customizable serialization of a URL String representation of a
218
[WHATWG URL][] object.
219
220
The URL object has both a `toString()` method and `href` property that return
221
string serializations of the URL. These are not, however, customizable in
222
any way. The `url.format(URL[, options])` method allows for basic customization
223
of the output.
224
225
For example:
226
227
```js
228
const myURL = new URL('https://a:b@你好你好?abc#foo');
229
230
console.log(myURL.href);
231
// Prints https://a:b@xn--6qqa088eba/?abc#foo
232
233
console.log(myURL.toString());
234
// Prints https://a:b@xn--6qqa088eba/?abc#foo
235
236
console.log(url.format(myURL, {fragment: false, unicode: true, auth: false}));
237
// Prints 'https://你好你好?abc'
238
```
239
240
*Note*: This variation of the `url.format()` method is currently considered to
241
be experimental.
242
243
## url.parse(urlString[, parseQueryString[, slashesDenoteHost]])
244
<!-- YAML
245
added: v0.1.25
246
-->
247
248
* `urlString` {string} The URL string to parse.
249
* `parseQueryString` {boolean} If `true`, the `query` property will always
250
be set to an object returned by the [`querystring`][] module's `parse()`
251
method. If `false`, the `query` property on the returned URL object will be an
252
unparsed, undecoded string. Defaults to `false`.
253
* `slashesDenoteHost` {boolean} If `true`, the first token after the literal
254
string `//` and preceding the next `/` will be interpreted as the `host`.
255
For instance, given `//foo/bar`, the result would be
256
`{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`.
257
Defaults to `false`.
258
259
The `url.parse()` method takes a URL string, parses it, and returns a URL
260
object.
261
262
A `TypeError` is thrown if `urlString` is not a string.
263
264
A `URIError` is thrown if the `auth` property is present but cannot be decoded.
265
266
## url.resolve(from, to)
267
<!-- YAML
268
added: v0.1.25
269
changes:
270
- version: v6.6.0
271
pr-url: https://github.com/nodejs/node/pull/8215
272
description: The `auth` fields are now kept intact when `from` and `to`
273
refer to the same host.
274
- version: v6.5.0, v4.6.2
275
pr-url: https://github.com/nodejs/node/pull/8214
276
description: The `port` field is copied correctly now.
277
- version: v6.0.0
278
pr-url: https://github.com/nodejs/node/pull/1480
279
description: The `auth` fields is cleared now the `to` parameter
280
contains a hostname.
281
-->
282
283
* `from` {string} The Base URL being resolved against.
284
* `to` {string} The HREF URL being resolved.
285
286
The `url.resolve()` method resolves a target URL relative to a base URL in a
287
manner similar to that of a Web browser resolving an anchor tag HREF.
288
289
For example:
290
291
```js
292
url.resolve('/one/two/three', 'four') // '/one/two/four'
293
url.resolve('http://example.com/', '/one') // 'http://example.com/one'
294
url.resolve('http://example.com/one', '/two') // 'http://example.com/two'
295
```
296
297
## Escaped Characters
298
299
URLs are only permitted to contain a certain range of characters. Spaces (`' '`)
300
and the following characters will be automatically escaped in the
301
properties of URL objects:
302
303
```txt
304
< > " ` \r \n \t { } | \ ^ '
305
```
306
307
For example, the ASCII space character (`' '`) is encoded as `%20`. The ASCII
308
forward slash (`/`) character is encoded as `%3C`.
309
310
## The WHATWG URL API
311
312
> Stability: 1 - Experimental
313
314
The `url` module provides an *experimental* implementation of the
315
[WHATWG URL Standard][] as an alternative to the existing `url.parse()` API.
316
317
```js
318
const URL = require('url').URL;
319
const myURL = new URL('https://example.org/foo');
320
321
console.log(myURL.href); // https://example.org/foo
322
console.log(myURL.protocol); // https:
323
console.log(myURL.hostname); // example.org
324
console.log(myURL.pathname); // /foo
325
```
326
327
*Note*: Using the `delete` keyword (e.g. `delete myURL.protocol`,
328
`delete myURL.pathname`, etc) has no effect but will still return `true`.
329
330
A comparison between this API and `url.parse()` is given below. Above the URL
331
`'http://user:[email protected]:8080/p/a/t/h?query=string#hash'`, properties of an
332
object returned by `url.parse()` are shown. Below it are properties of a WHATWG
333
`URL` object.
334
335
*Note*: WHATWG URL's `origin` property includes `protocol` and `host`, but not
336
`username` or `password`.
337
338
```txt
339
┌─────────────────────────────────────────────────────────────────────────────────────────┐
340
│ href │
341
├──────────┬──┬─────────────────────┬─────────────────┬───────────────────────────┬───────┤
342
│ protocol │ │ auth │ host │ path │ hash │
343
│ │ │ ├──────────┬──────┼──────────┬────────────────┤ │
344
│ │ │ │ hostname │ port │ pathname │ search │ │
345
│ │ │ │ │ │ ├─┬──────────────┤ │
346
│ │ │ │ │ │ │ │ query │ │
347
" http: // user : pass @ host.com : 8080 /p/a/t/h ? query=string #hash "
348
│ │ │ │ │ hostname │ port │ │ │ │
349
│ │ │ │ ├──────────┴──────┤ │ │ │
350
│ protocol │ │ username │ password │ host │ │ │ │
351
├──────────┴──┼──────────┴──────────┼─────────────────┤ │ │ │
352
│ origin │ │ origin │ pathname │ search │ hash │
353
├─────────────┴─────────────────────┴─────────────────┴──────────┴────────────────┴───────┤
354
│ href │
355
└─────────────────────────────────────────────────────────────────────────────────────────┘
356
(all spaces in the "" line should be ignored -- they are purely for formatting)
357
```
358
359
### Class: URL
360
#### Constructor: new URL(input[, base])
361
362
* `input` {string} The input URL to parse
363
* `base` {string|URL} The base URL to resolve against if the `input` is not
364
absolute.
365
366
Creates a new `URL` object by parsing the `input` relative to the `base`. If
367
`base` is passed as a string, it will be parsed equivalent to `new URL(base)`.
368
369
```js
370
const myURL = new URL('/foo', 'https://example.org/');
371
// https://example.org/foo
372
```
373
374
A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note
375
that an effort will be made to coerce the given values into strings. For
376
instance:
377
378
```js
379
const myURL = new URL({toString: () => 'https://example.org/'});
380
// https://example.org/
381
```
382
383
Unicode characters appearing within the hostname of `input` will be
384
automatically converted to ASCII using the [Punycode][] algorithm.
385
386
```js
387
const myURL = new URL('https://你好你好');
388
// https://xn--6qqa088eba/
389
```
390
391
Additional [examples of parsed URLs][] may be found in the WHATWG URL Standard.
392
393
#### url.hash
394
395
* {string}
396
397
Gets and sets the fragment portion of the URL.
398
399
```js
400
const myURL = new URL('https://example.org/foo#bar');
401
console.log(myURL.hash);
402
// Prints #bar
403
404
myURL.hash = 'baz';
405
console.log(myURL.href);
406
// Prints https://example.org/foo#baz
407
```
408
409
Invalid URL characters included in the value assigned to the `hash` property
410
are [percent-encoded][]. Note that the selection of which characters to
411
percent-encode may vary somewhat from what the [`url.parse()`][] and
412
[`url.format()`][] methods would produce.
413
414
#### url.host
415
416
* {string}
417
418
Gets and sets the host portion of the URL.
419
420
```js
421
const myURL = new URL('https://example.org:81/foo');
422
console.log(myURL.host);
423
// Prints example.org:81
424
425
myURL.host = 'example.com:82';
426
console.log(myURL.href);
427
// Prints https://example.com:82/foo
428
```
429
430
Invalid host values assigned to the `host` property are ignored.
431
432
#### url.hostname
433
434
* {string}
435
436
Gets and sets the hostname portion of the URL. The key difference between
437
`url.host` and `url.hostname` is that `url.hostname` does *not* include the
438
port.
439
440
```js
441
const myURL = new URL('https://example.org:81/foo');
442
console.log(myURL.hostname);
443
// Prints example.org
444
445
myURL.hostname = 'example.com:82';
446
console.log(myURL.href);
447
// Prints https://example.com:81/foo
448
```
449
450
Invalid hostname values assigned to the `hostname` property are ignored.
451
452
#### url.href
453
454
* {string}
455
456
Gets and sets the serialized URL.
457
458
```js
459
const myURL = new URL('https://example.org/foo');
460
console.log(myURL.href);
461
// Prints https://example.org/foo
462
463
myURL.href = 'https://example.com/bar'
464
// Prints https://example.com/bar
465
```
466
467
Getting the value of the `href` property is equivalent to calling
468
[`url.toString()`][].
469
470
Setting the value of this property to a new value is equivalent to creating a
471
new `URL` object using [`new URL(value)`][`new URL()`]. Each of the `URL`
472
object's properties will be modified.
473
474
If the value assigned to the `href` property is not a valid URL, a `TypeError`
475
will be thrown.
476
477
#### url.origin
478
479
* {string}
480
481
Gets the read-only serialization of the URL's origin. Unicode characters that
482
may be contained within the hostname will be encoded as-is without [Punycode][]
483
encoding.
484
485
```js
486
const myURL = new URL('https://example.org/foo/bar?baz');
487
console.log(myURL.origin);
488
// Prints https://example.org
489
```
490
491
```js
492
const idnURL = new URL('https://你好你好');
493
console.log(idnURL.origin);
494
// Prints https://你好你好
495
496
console.log(idnURL.hostname);
497
// Prints xn--6qqa088eba
498
```
499
500
#### url.password
501
502
* {string}
503
504
Gets and sets the password portion of the URL.
505
506
```js
507
const myURL = new URL('https://abc:[email protected]');
508
console.log(myURL.password);
509
// Prints xyz
510
511
myURL.password = '123';
512
console.log(myURL.href);
513
// Prints https://abc:[email protected]
514
```
515
516
Invalid URL characters included in the value assigned to the `password` property
517
are [percent-encoded][]. Note that the selection of which characters to
518
percent-encode may vary somewhat from what the [`url.parse()`][] and
519
[`url.format()`][] methods would produce.
520
521
#### url.pathname
522
523
* {string}
524
525
Gets and sets the path portion of the URL.
526
527
```js
528
const myURL = new URL('https://example.org/abc/xyz?123');
529
console.log(myURL.pathname);
530
// Prints /abc/xyz
531
532
myURL.pathname = '/abcdef';
533
console.log(myURL.href);
534
// Prints https://example.org/abcdef?123
535
```
536
537
Invalid URL characters included in the value assigned to the `pathname`
538
property are [percent-encoded][]. Note that the selection of which characters
539
to percent-encode may vary somewhat from what the [`url.parse()`][] and
540
[`url.format()`][] methods would produce.
541
542
#### url.port
543
544
* {string}
545
546
Gets and sets the port portion of the URL.
547
548
```js
549
const myURL = new URL('https://example.org:8888');
550
console.log(myURL.port);
551
// Prints 8888
552
553
// Default ports are automatically transformed to the empty string
554
// (HTTPS protocol's default port is 443)
555
myURL.port = '443';
556
console.log(myURL.port);
557
// Prints the empty string
558
console.log(myURL.href);
559
// Prints https://example.org/
560
561
myURL.port = 1234;
562
console.log(myURL.port);
563
// Prints 1234
564
console.log(myURL.href);
565
// Prints https://example.org:1234/
566
567
// Completely invalid port strings are ignored
568
myURL.port = 'abcd';
569
console.log(myURL.port);
570
// Prints 1234
571
572
// Leading numbers are treated as a port number
573
myURL.port = '5678abcd';
574
console.log(myURL.port);
575
// Prints 5678
576
577
// Non-integers are truncated
578
myURL.port = 1234.5678;
579
console.log(myURL.port);
580
// Prints 1234
581
582
// Out-of-range numbers are ignored
583
myURL.port = 1e10;
584
console.log(myURL.port);
585
// Prints 1234
586
```
587
588
The port value may be set as either a number or as a String containing a number
589
in the range `0` to `65535` (inclusive). Setting the value to the default port
590
of the `URL` objects given `protocol` will result in the `port` value becoming
591
the empty string (`''`).
592
593
If an invalid string is assigned to the `port` property, but it begins with a
594
number, the leading number is assigned to `port`. Otherwise, or if the number
595
lies outside the range denoted above, it is ignored.
596
597
#### url.protocol
598
599
* {string}
600
601
Gets and sets the protocol portion of the URL.
602
603
```js
604
const myURL = new URL('https://example.org');
605
console.log(myURL.protocol);
606
// Prints https:
607
608
myURL.protocol = 'ftp';
609
console.log(myURL.href);
610
// Prints ftp://example.org
611
```
612
613
Invalid URL protocol values assigned to the `protocol` property are ignored.
614
615
#### url.search
616
617
* {string}
618
619
Gets and sets the serialized query portion of the URL.
620
621
```js
622
const myURL = new URL('https://example.org/abc?123');
623
console.log(myURL.search);
624
// Prints ?123
625
626
myURL.search = 'abc=xyz';
627
console.log(myURL.href);
628
// Prints https://example.org/abc?abc=xyz
629
```
630
631
Any invalid URL characters appearing in the value assigned the `search`
632
property will be [percent-encoded][]. Note that the selection of which
633
characters to percent-encode may vary somewhat from what the [`url.parse()`][]
634
and [`url.format()`][] methods would produce.
635
636
#### url.searchParams
637
638
* {URLSearchParams}
639
640
Gets the [`URLSearchParams`][] object representing the query parameters of the
641
URL. This property is read-only; to replace the entirety of query parameters of
642
the URL, use the [`url.search`][] setter. See [`URLSearchParams`][]
643
documentation for details.
644
645
#### url.username
646
647
* {string}
648
649
Gets and sets the username portion of the URL.
650
651
```js
652
const myURL = new URL('https://abc:[email protected]');
653
console.log(myURL.username);
654
// Prints abc
655
656
myURL.username = '123';
657
console.log(myURL.href);
658
// Prints https://123:[email protected]
659
```
660
661
Any invalid URL characters appearing in the value assigned the `username`
662
property will be [percent-encoded][]. Note that the selection of which
663
characters to percent-encode may vary somewhat from what the [`url.parse()`][]
664
and [`url.format()`][] methods would produce.
665
666
#### url.toString()
667
668
* Returns: {string}
669
670
The `toString()` method on the `URL` object returns the serialized URL. The
671
value returned is equivalent to that of [`url.href`][] and [`url.toJSON()`][].
672
673
Because of the need for standard compliance, this method does not allow users
674
to customize the serialization process of the URL. For more flexibility,
675
[`require('url').format()`][] method might be of interest.
676
677
#### url.toJSON()
678
679
* Returns: {string}
680
681
The `toJSON()` method on the `URL` object returns the serialized URL. The
682
value returned is equivalent to that of [`url.href`][] and
683
[`url.toString()`][].
684
685
This method is automatically called when an `URL` object is serialized
686
with [`JSON.stringify()`][].
687
688
```js
689
const myURLs = [
690
new URL('https://www.example.com'),
691
new URL('https://test.example.org')
692
];
693
console.log(JSON.stringify(myURLs));
694
// Prints ["https://www.example.com/","https://test.example.org/"]
695
```
696
697
### Class: URLSearchParams
698
699
The `URLSearchParams` API provides read and write access to the query of a
700
`URL`. The `URLSearchParams` class can also be used standalone with one of the
701
four following constructors.
702
703
The WHATWG `URLSearchParams` interface and the [`querystring`][] module have
704
similar purpose, but the purpose of the [`querystring`][] module is more
705
general, as it allows the customization of delimiter characters (`&` and `=`).
706
On the other hand, this API is designed purely for URL query strings.
707
708
```js
709
const { URL, URLSearchParams } = require('url');
710
711
const myURL = new URL('https://example.org/?abc=123');
712
console.log(myURL.searchParams.get('abc'));
713
// Prints 123
714
715
myURL.searchParams.append('abc', 'xyz');
716
console.log(myURL.href);
717
// Prints https://example.org/?abc=123&abc=xyz
718
719
myURL.searchParams.delete('abc');
720
myURL.searchParams.set('a', 'b');
721
console.log(myURL.href);
722
// Prints https://example.org/?a=b
723
724
const newSearchParams = new URLSearchParams(myURL.searchParams);
725
// The above is equivalent to
726
// const newSearchParams = new URLSearchParams(myURL.search);
727
728
newSearchParams.append('a', 'c');
729
console.log(myURL.href);
730
// Prints https://example.org/?a=b
731
console.log(newSearchParams.toString());
732
// Prints a=b&a=c
733
734
// newSearchParams.toString() is implicitly called
735
myURL.search = newSearchParams;
736
console.log(myURL.href);
737
// Prints https://example.org/?a=b&a=c
738
newSearchParams.delete('a');
739
console.log(myURL.href);
740
// Prints https://example.org/?a=b&a=c
741
```
742
743
#### Constructor: new URLSearchParams()
744
745
Instantiate a new empty `URLSearchParams` object.
746
747
#### Constructor: new URLSearchParams(string)
748
749
* `string` {string} A query string
750
751
Parse the `string` as a query string, and use it to instantiate a new
752
`URLSearchParams` object. A leading `'?'`, if present, is ignored.
753
754
```js
755
const { URLSearchParams } = require('url');
756
let params;
757
758
params = new URLSearchParams('user=abc&query=xyz');
759
console.log(params.get('user'));
760
// Prints 'abc'
761
console.log(params.toString());
762
// Prints 'user=abc&query=xyz'
763
764
params = new URLSearchParams('?user=abc&query=xyz');
765
console.log(params.toString());
766
// Prints 'user=abc&query=xyz'
767
```
768
769
#### Constructor: new URLSearchParams(obj)
770
771
* `obj` {Object} An object representing a collection of key-value pairs
772
773
Instantiate a new `URLSearchParams` object with a query hash map. The key and
774
value of each property of `obj` are always coerced to strings.
775
776
*Note*: Unlike [`querystring`][] module, duplicate keys in the form of array
777
values are not allowed. Arrays are stringified using [`array.toString()`][],
778
which simply joins all array elements with commas.
779
780
```js
781
const { URLSearchParams } = require('url');
782
const params = new URLSearchParams({
783
user: 'abc',
784
query: ['first', 'second']
785
});
786
console.log(params.getAll('query'));
787
// Prints ['first,second']
788
console.log(params.toString());
789
// Prints 'user=abc&query=first%2Csecond'
790
```
791
792
#### Constructor: new URLSearchParams(iterable)
793
794
* `iterable` {Iterable} An iterable object whose elements are key-value pairs
795
796
Instantiate a new `URLSearchParams` object with an iterable map in a way that
797
is similar to [`Map`][]'s constructor. `iterable` can be an Array or any
798
iterable object. That means `iterable` can be another `URLSearchParams`, in
799
which case the constructor will simply create a clone of the provided
800
`URLSearchParams`. Elements of `iterable` are key-value pairs, and can
801
themselves be any iterable object.
802
803
Duplicate keys are allowed.
804
805
```js
806
const { URLSearchParams } = require('url');
807
let params;
808
809
// Using an array
810
params = new URLSearchParams([
811
['user', 'abc'],
812
['query', 'first'],
813
['query', 'second']
814
]);
815
console.log(params.toString());
816
// Prints 'user=abc&query=first&query=second'
817
818
// Using a Map object
819
const map = new Map();
820
map.set('user', 'abc');
821
map.set('query', 'xyz');
822
params = new URLSearchParams(map);
823
console.log(params.toString());
824
// Prints 'user=abc&query=xyz'
825
826
// Using a generator function
827
function* getQueryPairs() {
828
yield ['user', 'abc'];
829
yield ['query', 'first'];
830
yield ['query', 'second'];
831
}
832
params = new URLSearchParams(getQueryPairs());
833
console.log(params.toString());
834
// Prints 'user=abc&query=first&query=second'
835
836
// Each key-value pair must have exactly two elements
837
new URLSearchParams([
838
['user', 'abc', 'error']
839
]);
840
// Throws TypeError: Each query pair must be a name/value tuple
841
```
842
843
#### urlSearchParams.append(name, value)
844
845
* `name` {string}
846
* `value` {string}
847
848
Append a new name-value pair to the query string.
849
850
#### urlSearchParams.delete(name)
851
852
* `name` {string}
853
854
Remove all name-value pairs whose name is `name`.
855
856
#### urlSearchParams.entries()
857
858
* Returns: {Iterator}
859
860
Returns an ES6 Iterator over each of the name-value pairs in the query.
861
Each item of the iterator is a JavaScript Array. The first item of the Array
862
is the `name`, the second item of the Array is the `value`.
863
864
Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`].
865
866
#### urlSearchParams.forEach(fn[, thisArg])
867
868
* `fn` {Function} Function invoked for each name-value pair in the query.
869
* `thisArg` {Object} Object to be used as `this` value for when `fn` is called
870
871
Iterates over each name-value pair in the query and invokes the given function.
872
873
```js
874
const URL = require('url').URL;
875
const myURL = new URL('https://example.org/?a=b&c=d');
876
myURL.searchParams.forEach((value, name, searchParams) => {
877
console.log(name, value, myURL.searchParams === searchParams);
878
});
879
// Prints:
880
// a b true
881
// c d true
882
```
883
884
#### urlSearchParams.get(name)
885
886
* `name` {string}
887
* Returns: {string} or `null` if there is no name-value pair with the given
888
`name`.
889
890
Returns the value of the first name-value pair whose name is `name`. If there
891
are no such pairs, `null` is returned.
892
893
#### urlSearchParams.getAll(name)
894
895
* `name` {string}
896
* Returns: {Array}
897
898
Returns the values of all name-value pairs whose name is `name`. If there are
899
no such pairs, an empty array is returned.
900
901
#### urlSearchParams.has(name)
902
903
* `name` {string}
904
* Returns: {boolean}
905
906
Returns `true` if there is at least one name-value pair whose name is `name`.
907
908
#### urlSearchParams.keys()
909
910
* Returns: {Iterator}
911
912
Returns an ES6 Iterator over the names of each name-value pair.
913
914
```js
915
const { URLSearchParams } = require('url');
916
const params = new URLSearchParams('foo=bar&foo=baz');
917
for (const name of params.keys()) {
918
console.log(name);
919
}
920
// Prints:
921
// foo
922
// foo
923
```
924
925
#### urlSearchParams.set(name, value)
926
927
* `name` {string}
928
* `value` {string}
929
930
Sets the value in the `URLSearchParams` object associated with `name` to
931
`value`. If there are any pre-existing name-value pairs whose names are `name`,
932
set the first such pair's value to `value` and remove all others. If not,
933
append the name-value pair to the query string.
934
935
```js
936
const { URLSearchParams } = require('url');
937
938
const params = new URLSearchParams();
939
params.append('foo', 'bar');
940
params.append('foo', 'baz');
941
params.append('abc', 'def');
942
console.log(params.toString());
943
// Prints foo=bar&foo=baz&abc=def
944
945
params.set('foo', 'def');
946
params.set('xyz', 'opq');
947
console.log(params.toString());
948
// Prints foo=def&abc=def&xyz=opq
949
```
950
951
#### urlSearchParams.sort()
952
953
Sort all existing name-value pairs in-place by their names. Sorting is done
954
with a [stable sorting algorithm][], so relative order between name-value pairs
955
with the same name is preserved.
956
957
This method can be used, in particular, to increase cache hits.
958
959
```js
960
const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
961
params.sort();
962
console.log(params.toString());
963
// Prints query%5B%5D=abc&query%5B%5D=123&type=search
964
```
965
966
#### urlSearchParams.toString()
967
968
* Returns: {string}
969
970
Returns the search parameters serialized as a string, with characters
971
percent-encoded where necessary.
972
973
#### urlSearchParams.values()
974
975
* Returns: {Iterator}
976
977
Returns an ES6 Iterator over the values of each name-value pair.
978
979
#### urlSearchParams\[@@iterator\]()
980
981
* Returns: {Iterator}
982
983
Returns an ES6 Iterator over each of the name-value pairs in the query string.
984
Each item of the iterator is a JavaScript Array. The first item of the Array
985
is the `name`, the second item of the Array is the `value`.
986
987
Alias for [`urlSearchParams.entries()`][].
988
989
```js
990
const { URLSearchParams } = require('url');
991
const params = new URLSearchParams('foo=bar&xyz=baz');
992
for (const [name, value] of params) {
993
console.log(name, value);
994
}
995
// Prints:
996
// foo bar
997
// xyz baz
998
```
999
1000
### require('url').domainToASCII(domain)