Archive for April, 2011

JavaScript URL Parsing

Apr 24 2011 Published by under Programming

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:

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

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:

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

No responses yet