
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Parse URL in JavaScript
Parsing an URL
It is very simple to parse an URL in javascript by using DOM method rather than Regular expressions. If regular expressions are used then code will be much more complicated. In DOM method just a function call will return the parsed URL.
In the following example, initially a function is created and then an anchor tag "a" is created inside it using a DOM method. Later on the provided URL was assigned to the anchor tag using href. Now, when function returns the parts of the URL, it tries to return the parsed parts as shown in the output. Since the url is parsed, JSON.stringify() method is used so as to display the output.
Example
<html> <body> <script> function URL(url) { var urlParser = document.createElement('a'); urlParser.href = url; return { protocol: urlParser.protocol, host: urlParser.host, hostname: urlParser.hostname, port: urlParser.port, pathname: urlParser.pathname, search: urlParser.search, hash: urlParser.hash }; } document.write(JSON.stringify(URL("https://www.youtube.com/watch?v=tNJJSrfKYwQ"))); </script> </body> </html>
Output{"protocol":"https:","host":"www.youtube.com","hostname":"www.youtube.com","port":"","pathname":"/watch","search":"?v=tNJJSrfKYwQ","hash":""}
Advertisements