Last Updated: February 25, 2016
·
1.439K
· 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'

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside