Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript在URL中获取子字符串_Javascript - Fatal编程技术网

javascript在URL中获取子字符串

javascript在URL中获取子字符串,javascript,Javascript,在我的网站中,我使用: - www.example.com/es/index.html - www.example.com/en/index.html - www.example.com/ch/index.html 如何轻松获得价值语言?(es或en或ch) 其中url是您正在解析的url。也许用“位置”来获得它 您可以使用: var url = 'www.example.com/es/index.html' var lang = url.split('/')[1] 可以使用var lang

在我的网站中,我使用:

- www.example.com/es/index.html
- www.example.com/en/index.html
- www.example.com/ch/index.html
如何轻松获得价值语言?(es或en或ch)

其中url是您正在解析的url。也许用“位置”来获得它

您可以使用:

var url = 'www.example.com/es/index.html'
var lang = url.split('/')[1]

可以使用
var lang=location.pathname.split('/')[1]


这假设语言目录总是在
.com

之后,正如u\u mulder所建议的,您可以使用
文档。位置
如下:

document.location.href.split("/")[1];
而所有这些

str.split("/")[1]
解决方案很好,我想建议使用正则表达式(如果只是为了完整性)。

使用

str = "www.example.com/es/index.html";
str.match(/www\.example\.com\/(.+)\//)[1]

同样有效,而且它还可以正确匹配字符串,如:

"http://www.example.com/es/index.html"

fiddle:

将每个index.html更改为不同的内容,很容易。。。或者获取URL并解析它。@u\u mulder好主意!document.location是一个对象而不是字符串,因此这只是抛出一个错误
"http://www.example.com/es/index.html"