# How to parse an URL in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

## 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

Live Demo

<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
};
}
</html>