Last active
May 13, 2022 03:13
-
-
Save shazron/cafb12db9e69f5e68901b82cf1a63272 to your computer and use it in GitHub Desktop.
alternative to url-join or proper-url-join node modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path') | |
const assert = require('assert') | |
function urlJoinPath(url, pathToAdd) { | |
const u = new URL(url) | |
u.pathname = path.posix.join(u.pathname, pathToAdd) | |
return u.href | |
} | |
let result1 = urlJoinPath('https://foo.bar/a/b', 'recordlogin') | |
console.log('url no trailing slash, pathToAdd no leading slash', '-->', result1) // result: 'https://foo.bar/a/b/recordlogin' | |
let result2 = urlJoinPath('https://foo.bar/a/b', '/recordlogin') | |
console.log('url no trailing slash, pathToAdd has leading slash', '-->', result2) // result: 'https://foo.bar/a/b/recordlogin' | |
let result3 = urlJoinPath('https://foo.bar/a/b/', 'recordlogin') | |
console.log('url has trailing slash, pathToAdd no leading slash', '-->', result3) // result: 'https://foo.bar/a/b/recordlogin' | |
let result4 = urlJoinPath('https://foo.bar/a/b/', '/recordlogin') | |
console.log('url has trailing slash, pathToAdd has leading slash', '-->', result4) // result: 'https://foo.bar/a/b/recordlogin' | |
assert.strictEqual(result1, result2) | |
assert.strictEqual(result1, result3) | |
assert.strictEqual(result3, result4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
code is https://creativecommons.org/publicdomain/mark/1.0/