如何找到位置路径名的第3部分?

时间:2022-03-19 09:26:32

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".

如果我使用document.location.pathname,我会得到“/first/sedond/third.html”。如果我使用document.location.pathname [1],我会得到“f”。

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

如何使用document.location.pathname获得“第一”部分?

Thanks in advance.

提前致谢。

1 个解决方案

#1


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

你问了两个不同的问题 - 这里都是答案。 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);
}

#1


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

你问了两个不同的问题 - 这里都是答案。 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);
}