Last Updated: February 25, 2016
·
1.132K
· livingston

Change parts of URI

Use the nifty DOM api to manipulate parts of an URI.

Let's see how we can manipulate parts of an URL
http://google.com/
into
https://mail.google.com/mail/u/0/?preview=false#inbox

var uri = document.createElement('a');

uri.href = 'http://google.com/';      //set the URI

uri.protocol = 'https:';          //change protocol
uri.hostname = 'mail.google.com'; //change domain
uri.hash = 'inbox';
uri.pathname = 'mail/u/0/';
uri.search = 'preview=false';

console.log(uri.href);            //get the modified url
=> "https://mail.google.com/mail/u/0/?preview=false#inbox'