Created
October 25, 2019 09:36
-
-
Save hadaytullah/a364a3cf1e88de406af06fec8a49cdf2 to your computer and use it in GitHub Desktop.
Parses a url into its different parts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var UrlParser = function() { | |
this.result = {}; | |
}; | |
UrlParser.prototype.parse = function(url) { | |
var urlWithoutScheme = url.split('://')[1]; | |
var pathStartIndex = urlWithoutScheme.indexOf('/'); | |
var queryStartIndex = urlWithoutScheme.indexOf('?'); | |
var hostAndPort; | |
if (pathStartIndex > 0) { | |
hostAndPort = urlWithoutScheme.split('/')[0]; | |
var path; | |
if (queryStartIndex > 0) { | |
path = urlWithoutScheme.slice(pathStartIndex+1, queryStartIndex); | |
} else { | |
path = urlWithoutScheme.slice(pathStartIndex+1); | |
} | |
this.parsePath(path); | |
} else { | |
hostAndPort = urlWithoutScheme.split('?')[0]; | |
} | |
if (queryStartIndex > 0) { | |
var query = urlWithoutScheme.split('?')[1]; | |
this.parseQuery(query); | |
} | |
this.parseHost(hostAndPort); | |
this.parsePort(hostAndPort); | |
return this.result; | |
}; | |
UrlParser.prototype.parseHost = function(hostAndPort) { | |
this.result.host = hostAndPort.split(':')[0]; | |
return this.result.host; | |
}; | |
UrlParser.prototype.parsePort = function(hostAndPort) { | |
var parts = hostAndPort.split(':'); | |
if (parts.length > 1 && parts[1].length > 0) { | |
this.result.port = parseInt(parts[1]); | |
} | |
return this.result.port; | |
}; | |
UrlParser.prototype.parsePath = function(path) { | |
this.result.pathSegments = path.split('/'); | |
return this.result.pathSegments; | |
}; | |
UrlParser.prototype.parseQuery = function(query) { | |
this.result.queryParameters = query.split('&'); | |
return this.result.queryParameters; | |
}; | |
var parser = new UrlParser(); | |
console.log(parser.parse("http://www.unity.com/index.html?val=abc&tim=lol lol")); | |
//console.log(parser.parse("http://www.unity.com:8080/api//user?var=20&&tim=40/")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment