From 0fac27d546189cbe3b2b84688f4fc9af9219b2d1 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Wed, 24 Feb 2021 13:53:59 +0100 Subject: [PATCH] doc: add url.resolve replacement example Fixes: https://github.com/nodejs/node/issues/37492 PR-URL: https://github.com/nodejs/node/pull/37501 Reviewed-By: James M Snell Reviewed-By: Darshan Sen --- doc/api/url.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/doc/api/url.md b/doc/api/url.md index ad6455f2a1f545..e78b15d09d28d1 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -1362,6 +1362,24 @@ url.resolve('http://example.com/', '/one'); // 'http://example.com/one' url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' ``` +You can achieve the same result using the WHATWG URL API: + +```js +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' +``` + ## Percent-encoding in URLs