JavaScript URL Parsing

Apr 24 2011

Many web frameworks have URLs in the format of domain/category/page, but what if there’s a need for that outside of the framework, like in client-side scripting? Two lines of code is enough for getting those URL parameters:

[cc lang=”javascript”]

var url = /(\w+):\/\/([\w.]+(?:\:8000)?)\/(\S*)\/(\S*)\//;
var result = “http://127.0.0.1:8000/category/page/”.match(url);

[/cc]

One special feature of JavaScript regular expressions is (?…) is a group that does not show in the result array.

If you wanted to map the result to different actions:
[cc lang=”javascript”]

if (result != null) {
switch(result[4]){ //page
case ‘page1’:
//code block1
break;
}
}

[/cc]

No responses yet