Javascript: Splitting a URL into parts using Regex
Sep 6, 2014 •
javaScript
How to split a URL into different parts in JS by using regex
JavaScript (js) is a lightweight, interpreted, object-oriented language with first-class functions, most known as the scripting language for Web pages. Most of the web application developers, designers etc.. use js on a daily basis. Recently I got selected for Google Summer of code 2014, and a part of my project was related to JavaScript where I had to make use of JavaScript for splitting a URL into corresponding parts. When I googled this, I came across many tutorials but later on I set down to write a function making use of the powerful JavaScript Regex (thanks to my friend, Arjun, who helped me in writing this). Here is the code that I wrote:
One obvious question that comes to everyone’s mind is that, what the hell does this code do ?. I can explain that. Even though this code looks very huge, its functionality is very simple. Here I’m assuming that you have the URL to split it in a variable named “q”. If so, the URL is passed as an argument to the function printer and the splitting occurs. After the splitting, 5 new JavaScript variables are created namely scheme, host, port, path **and **sub.
For example, consider that the URL saved in the variable q is “http:/security.securethelock.com:443/hey”. After the splitting, the 5 new variables will be created with the following values in it:
scheme: http://
host: securethelock.com
port: 443
path: hey
sub: security.securethelock.com
If port is not specified, the default value, 80, will be stored. If q is a main domain (and not a subdomain) like “http://www.securethelock.com”, sub = host = securethelock.com . If path is not specified, the corresponding variable will be empty.
Anirudh Anand
Product Security ♥ | CTF - @teambi0s | Security Trainer - @7asecurity | certs - eWDP, OSCP, OSWE