Javascript Append Url Path

July 27, 2021

URL

// http://www.mydomain.com/hello"
new URL('hello', 'http://www.mydomain.com').href    // http://www.mydomain.com/hello
new URL('/hello', 'http://www.mydomain.com').href   // http://www.mydomain.com/hello
new URL('hello/', 'http://www.mydomain.com').href   // http://www.mydomain.com/hello/
new URL('hello', 'http://www.mydomain.com/').href   // http://www.mydomain.com/hello
new URL('/hello', 'http://www.mydomain.com/').href  // http://www.mydomain.com/hello
new URL('hello/', 'http://www.mydomain.com/').href  // http://www.mydomain.com/hello/
new URL('hello', 'http://www.mydomain.com/page/').href  // http://www.mydomain.com/page/hello"

new URL('hello', 'http://www.mydomain.com/page').href   // http://www.mydomain.com/hello"
new URL('/hello', 'http://www.mydomain.com/page/').href // http://www.mydomain.com/hello"
new URL('/hello', 'http://www.mydomain.com/page').href  // http://www.mydomain.com/hello"

References:

url-join

You could use url-join but there are still some edge cases and no longer maintained since 2019.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.