tags:

views:

63

answers:

1

I want to get 'second' in the following sample web address.

http://www.mywebsite.com/first/sedond/third.html

"first" can be any length. i.e. contact, images etc

If I use document.location.pathname, I get "/first/sedond/third.html". If I use document.location.pathname[1], I get "f".

How can I get "first" part by using document.location.pathname?

Thanks in advance.

+3  A: 

You asked two different questions - here are both answers. 8-)

"How can I get 'first' part" - like this:

// Strip the first slash, else IE and FF give different results.
var pathname = document.location.pathname.substring(1);
var parts = pathname.split(/\//);
var result = parts[0];

"I want to get 'second'" - like this:

// Strip the first slash, else IE and FF give different results.
var pathname = document.location.pathname.substring(1);
var parts = pathname.split(/\//);
if (parts.length > 1 ) {
    var result = parts[1];
    document.write(result);
}
RichieHindle
I'm curious: Do the regexes need the "g" flag?
Josh Stodola
@Josh: Empirically no, but I couldn't easily find any official documentation to back that up.
RichieHindle