如何从Javascript中的URL中获取一个目录,省略域名?

时间:2017-08-30 09:27:00

标签: javascript

我有一个如下所示的域名:

http://www.example.com/abc/xyz/something_something

或者有时只是:

http://www.example.com/abc/

在任何一种情况下,想要只是 abc部分。我找到了this answer,它建议使用以下代码:

document.URL.substr(0,document.URL.lastIndexOf('/'))

返回:

http://www.example.com/abc/xyz/

如何扩展上述代码以提取第一个目录名?

请注意,它总是域名后的第一个目录,目录始终是3个字母的代码。

3 个答案:

答案 0 :(得分:3)

你得到的路径是:

window.location.pathname // "/questions/45956695/how-can-i-get-just-a-directory-from-the-url-in-javascript-omitting-the-domain#"

然后拆分出第一个参数:



// (Can't use window.location in snippets)
var pathname = "/questions/45956695/how-can-i-get-just-a-directory-from-the-url-in-javascript-omitting-the-domain#"

var p = pathname.split('/')[1]
console.log(p);




答案 1 :(得分:0)

子字符串location.pathname

location.pathname.substring(1,4)

答案 2 :(得分:0)

我会使用正则表达式:

const str = 'http://www.example.com/abc/xyz/something_something'
const match = str.match(/https?\:\/\/[a-z.]+\/([a-z0-9]+)\/?/)
// match[1] === 'abc'
相关问题