Welcome folks today in this blog post we will be parsing a website url
and extracting hostname,query string
and pathname in javascript. All the full source code of application is shown below.
Get Started
In order to get started just make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>Parse URL in Javascript</title> </head> <body></body> <script> const url = new URL("https://freemediatools.com/encryptpdf"); console.log(url.href); // => 'http://example.com/path/index.html' </script> </html> |
Now if you open your browser and inside console you will see that
Now we will be extracting the query string
inside the website url as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>Parse URL in Javascript</title> </head> <body></body> <script> const url = new URL("https://freemediatools.com/encryptpdf?message=hello&who=world"); console.log(url.search); // => 'http://example.com/path/index.html' </script> </html> |
Now we will extract the hostname
present inside the website as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>Parse URL in Javascript</title> </head> <body></body> <script> const url = new URL("https://freemediatools.com/encryptpdf"); console.log(url.hostname); // => 'http://example.com/path/index.html' </script> </html> |
Now we will be extracting the pathname
present inside the website url
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>Parse URL in Javascript</title> </head> <body></body> <script> const url = new URL("https://freemediatools.com/encryptpdf?path=name"); console.log(url.pathname); // => 'http://example.com/path/index.html' </script> </html> |
Now we will be extracting the hash
value from the website url as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>Parse URL in Javascript</title> </head> <body></body> <script> const url = new URL("https://freemediatools.com/encryptpdf?path=name#name"); console.log(url.hash); // => 'http://example.com/path/index.html' </script> </html> |
Now we will be getting the value of query parameters
present inside the website url as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <head> <title>Parse URL in Javascript</title> </head> <body></body> <script> const url = new URL("https://freemediatools.com/encryptpdf?path=name&second=gautam"); console.log(url.searchParams.get('path')); console.log(url.searchParams.get('second')); </script> </html> |