Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.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中提取location.href的一部分?_Javascript_Regex - Fatal编程技术网

如何在JavaScript中提取location.href的一部分?

如何在JavaScript中提取location.href的一部分?,javascript,regex,Javascript,Regex,在本例中,从location.href提取“first”的regexp是什么,例如: 既然您要求一个正则表达式解决方案,那么它就是: ^(?:[^:]+://)?[^/]+/([^/]+) 您可以使用window.location.host和window.location.search 只需查看详细信息可能不是您问题的答案,但如果您是用Javascript编写的,您可能希望使用location.pathname,而不是自己从整个href中提取它。真的吗?一个正则表达式,当它可以作为一个属性使用时

在本例中,从location.href提取“first”的regexp是什么,例如:


既然您要求一个正则表达式解决方案,那么它就是:

^(?:[^:]+://)?[^/]+/([^/]+)
您可以使用window.location.host和window.location.search
只需查看详细信息

可能不是您问题的答案,但如果您是用Javascript编写的,您可能希望使用location.pathname,而不是自己从整个href中提取它。

真的吗?一个正则表达式,当它可以作为一个属性使用时?@annakata:嗯,这就是cdillon要求的。但是,是的,有点倒退。@annakata:location.pathname也需要一些后期处理,因为OP似乎只要求“第一”部分。诚然,这可以通过split(“/”[0]实现,但是a)我看不到regex的真正缺点,b)出于某种原因,他可能也想匹配URL的其余部分。是的,你是对的。我稍微更改了正则表达式(使第一个组成为非捕获组),所以现在它应该给您以下内容:[“”,“first”]。数组位置0始终是整个匹配项,数组位置1是匹配组1。我使用location.pathname,但感谢正则表达式的回答,我会研究它。@CMS:因为裸location.pathname不能回答这个问题。+1。Regex不应该是首选!location.pathname.split(“/”)[1]比类似的正则表达式更容易理解。感谢您提醒我有关split的事情-当我有/first/和/first/second时,这很好用/ ^http://[^/]+/([^/]+)
var re = /^http:\/\/(www.)?mydomain\.com\/([^\/]*)\//;
var url = "http://mydomain.com/first/";

if(re.test(url)) {
  var matches = url.match(re);
  return matches[2]; // 0 contains whole URL, 1 contains optional "www", 2 contains last group
}