views:

132

answers:

3

I have a URL like:

http://url.test.com/account/name/pages/Stuff.html

I want to take 'Stuff' and apply that as a class to body.

<body class="Stuff">

...

</body>
  1. How can I get the current URL?

  2. How can I extract the text 'Stuff' after the final '/'

  3. Then add the class 'Stuff' to body?

+2  A: 
1. url=location.href

2. fname=url.match(/.*\/(.*)\./)[1]

3. document.body.className=fname
S.Mark
Can someone expand on this a little further?Possibly give me a full example with bits and pieces require?
danit
+3  A: 

Not the shortest of code but substring is pretty fast so...

var page = window.location.href;
page = page.substring(page.lastIndexOf('/') + 1);
page = page.substring(0, page.lastIndexOf('.'));
document.body.className = page;

edited because I forgot to include part 3

cballou
This is certainly much better than using regex.
DisgruntledGoat
It should be noted that `substring` is being used here and not `substr`. The difference being that `substring` takes an index as its second parameter as opposed to a length.
Justin Johnson
A: 

See: stackoverflow.com:how-can-i-add-a-class-to-the-body-tag-using-jquery

I wanted to say that this question is a duplicate but I think your title expresses the problem better.

slebetman