Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Join Relative URLs in JavaScript

Tags:

I want to join two strings each representing a relative URL in Javascript.

I want to join the base URL http://www.adress.com/more/evenmore with the following examples:

  1. ../../adress (with the expected output: http://www.adress.com/adress)
  2. ../adress (with the expected output http://www.adress.com/more/adress)

What would be the best way? I was thinking of using regexp and checking
how many ../ preceed the relative URL, then subtracting that amount from the baseurl and adding them to what is left.

like image 968
heffaklump Avatar asked Apr 20 '10 15:04

heffaklump


1 Answers

8 years later, many browsers (except for Internet Explorer) support the URL constructor (URL(url [, base])).

> new URL('../address', 'http://www.adress.com/more/evenmore/').href "http://www.adress.com/more/address" > new URL('../../address', 'http://www.adress.com/more/evenmore/').href "http://www.adress.com/address" 
like image 64
ning Avatar answered Nov 17 '22 09:11

ning