- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to parse an 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":""}
- Related Articles
- How to parse JSON object in JavaScript?
- How to parse an XML in JSP?
- How to get an object containing parameters of current URL in JavaScript?
- How to get current URL in JavaScript?
- How to validate URL address in JavaScript?
- How to parse float with two decimal places in JavaScript?
- How to parse a string to an int in C++?
- How to encode and decode a URL in JavaScript?
- Parse array to equal intervals in JavaScript
- How to parse a string from a JavaScript array?
- How to decode a URL using JavaScript function?
- How to encode a URL using JavaScript function?
- How to get the current URL with JavaScript?
- How to create a URL object using JavaScript?
- Converting whitespace string to url in JavaScript

Advertisements