diff options
Diffstat (limited to 'js')
-rw-r--r-- | js/url.ts | 19 | ||||
-rw-r--r-- | js/url_search_params.ts | 17 | ||||
-rw-r--r-- | js/url_test.ts | 16 |
3 files changed, 48 insertions, 4 deletions
@@ -8,7 +8,7 @@ interface URLParts { hostname: string; port: string; path: string; - query: string; + query: string | null; hash: string; } @@ -192,15 +192,26 @@ export class URL { } get search(): string { + if (this._parts.query === null || this._parts.query === "") { + return ""; + } + return this._parts.query; } set search(value: string) { value = String(value); - if (value.charAt(0) !== "?") { - value = `?${value}`; + let query: string | null; + + if (value === "") { + query = null; + } else if (value.charAt(0) !== "?") { + query = `?${value}`; + } else { + query = value; } - this._parts.query = value; + + this._parts.query = query; this._updateSearchParams(); } diff --git a/js/url_search_params.ts b/js/url_search_params.ts index 13b272476..1d9aa43b3 100644 --- a/js/url_search_params.ts +++ b/js/url_search_params.ts @@ -1,8 +1,10 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { URL } from "./url"; import { requiredArguments } from "./util"; export class URLSearchParams { private params: Array<[string, string]> = []; + private url: URL | null = null; constructor(init: string | string[][] | Record<string, string> = "") { if (typeof init === "string") { @@ -30,6 +32,20 @@ export class URLSearchParams { } } + private updateSteps(): void { + if (this.url === null) { + return; + } + + let query: string | null = this.toString(); + if (query === "") { + query = null; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this.url as any)._parts.query = query; + } + /** Appends a specified key/value pair as a new search parameter. * * searchParams.append('name', 'first'); @@ -56,6 +72,7 @@ export class URLSearchParams { i++; } } + this.updateSteps(); } /** Returns all the values associated with a given search parameter diff --git a/js/url_test.ts b/js/url_test.ts index 5744aa568..1861ef118 100644 --- a/js/url_test.ts +++ b/js/url_test.ts @@ -141,3 +141,19 @@ test(function urlBaseString(): void { ); assertEquals(url.href, "https://foo:bar@baz.qat:8000/foo/bar?baz=foo#qux"); }); + +test(function deletingAllParamsRemovesQuestionMarkFromURL(): void { + const url = new URL("http://example.com/?param1¶m2"); + url.searchParams.delete("param1"); + url.searchParams.delete("param2"); + assertEquals(url.href, "http://example.com/"); + assertEquals(url.search, ""); +}); + +test(function removingNonExistentParamRemovesQuestionMarkFromURL(): void { + const url = new URL("http://example.com/?"); + assertEquals(url.href, "http://example.com/?"); + url.searchParams.delete("param1"); + assertEquals(url.href, "http://example.com/"); + assertEquals(url.search, ""); +}); |