Take the 2-minute tour ×

I have a JavaScript script I need help modifying...
I'd like to have URL parts extracted and set as classes of the html element.

var loc = window.location.pathname.match(REGEX_CODE_GOES_HERE);
// document.documentElement is the html element, this adds the class
if(loc) document.documentElement.className += " " + loc[1].toLowerCase();

The hard part is the regex; this is how it should work:

Example URL:


Should return (as classes of html element, of course):

lists pages viewpage aspx id 12

Feel free to edit the code around in anyway you seem fit...

Thanks in advance!

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

something like

var split = window.location.pathname.split(/\/|\?|&|=|\./g);

or if you want all in one string:

var classes = window.location.pathname.toLowerCase().replace(/\/|\?|&|=|\./g," ")

might do what you want

share|improve this answer
I'd suggest using \W instead of specific chars if javascript supports this. –  Lucas Moeskops Nov 25 '10 at 10:57
but there might be non-word characters in parameters that you do not want to be delimiters –  morja Nov 25 '10 at 11:02
Thank you, it works. –  Tylerr Nov 25 '10 at 12:04
add comment
var matches = window.location.pathname.replace(/http:\/\/[^\/]+\//,'').match(/[\w\-\.!~\*\'"(),]+/g);

The regex complies with RFC 1738.

Converting each array element to lowercase should then be a trivial matter.

share|improve this answer
This only will not work. You can join this solution, to the previous, like that: var loc = window.location.pathname.replace(/http:\/\/[^\/]+\//,'').split(/\/|\?|&|=|\./g); –  Alexandre Nov 25 '10 at 10:59
@Alexandre: I suggest you test it before making a comment that it "will not work" –  stillstanding Nov 25 '10 at 11:01
Sorry @stillstanding, but I've tested on firebug, and it worked! I've only replaced 'window.location.pathname' with the given example URL. But your solution, after the last edition is working as well. –  Alexandre Nov 25 '10 at 11:24
add comment
var match = url.match(/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
var protocol = match[1],
    domain   = match[2],
    path     = match[3],
    query    = match[4],
    fragment = match[5];
share|improve this answer
add comment

Your Answer


