Javascript URL Api

The URL interface is used to parse, generate, normalize and encode URLs.

It helps you to easily read and edit the components of a URL.

Use of

We generate the current URL using the URL() api.

const url = new URL('http://phpexample.net:80/search?q=test1#test2')

now we can access some properties under the url variable.

hash -> returns if there is a value ending with #. The result in our example;

console.log(url.hash); 
// #test2

host -> returns the domain name along with the port. The result in our example;

console.log(url.host); 
// phpexample.net:80

hostname -> returns the domain name. The result in our example;

console.log(url.hostname); 
// phpexample.net

href -> returns the entire current url. The result in our example;

console.log(url.href); 
// http://phpexample.net:80/search?q=test1#test2

origin -> returns domain and port with schema. The result in our example;

console.log(url.origin); 
// https://phpexample.net:80

pathname -> returns the characters after /. This excludes query strings and fragments. The output in our example is;

console.log(url.pathname); 
// /search

port -> returns the port. The result in our example;

console.log(url.port); 
// 80

protocol -> returns the protocol of the url. The result in our example;

console.log(url.protocol); 
// http:

search -> returns query strings, that is, the ones after the question mark. The result in our example;

console.log(url.search); 
// ?q=test1

searchParams -> returns a URLSearchParams object, so you can get or add query strings with methods like get() and set(). The output in our example is;

console.log(url.searchParams.get('q')); 
// test

url.searchParams.set('type', '3')
console.log(url.href);
// https://phpexample.net:80/search?q=test1&type=3#test2

You can also do URL validation. 

try {
    new URL('is this url correct, i don't think so?')
} catch (e) {
    console.log(e)
    // TypeError: Failed to construct 'URL': Invalid URL
}

It's pretty easy to manipulate URLs. If I wanted to change our example url to phpexample.net;

url.hostname = 'phpexample.net';
url.protocol = 'http'
console.log(url.href);
// http:/phpexample.net/search?q=test1&type=3#test2

That's it, see you in the next lesson :)

Comments

There are no comments, make the firs comment