2011-04-20 170 views
15

我需要在JavaScript中的url中获得斜杠后的第一个单词,我假设使用正则表达式会是理想的。正则表达式在URL中的斜杠后获得第一个字

这里是什么样的URL可以可能看起来像一个想法:

粗体字正是我所需要的正则表达式匹配的每个场景,所以基本上只有第一部分的斜线后,不管有多少进一步的斜线有。

我在这里完全失去,感谢帮助。

+4

技术上,经过你的例子斜线是“mysite的”第一个字......你想要的是在URL的路径的第一部分零件。 – 2011-04-20 19:20:45

回答

30

JavaScript with RegEx。这将匹配任何东西后,直到我们遇到另一个/。

window.location.pathname.replace(/^\/([^\/]*).*$/, '$1'); 
+0

伟大的答案我的朋友 – JAF 2016-01-22 18:14:14

+0

伟大的工程,我thx。 – Gabbax0r 2017-05-02 11:45:03

+0

当url是www.a.com/1/2时,我想要/ 1 /后退。当网址是www.a.com,我想/回,这可以在一个单一的正则表达式中完成吗? – techguy2000 2017-11-21 18:24:00

2

尝试用:

var url = 'http://mysite.com/section-with-dashes/'; 
var section = url.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[0]; 
+0

我可能错了,但我认为它应该是'[1];'http://jsfiddle.net/AvHd3/ – Squirrl 2014-03-04 01:40:47

-1
$url = 'http://mysite.com/section/subsection'; 

$path = parse_url($url, PHP_URL_PATH); 

$components = explode('/', $path); 

$first_part = $components[0]; 
+3

出于某种原因,我在考虑JavaScript解释器不会喜欢你的PHP解决方案。 – 2011-04-20 19:48:49

+1

闪烁几次之后,你可能是对的......但是因为有很多人认为Javascript可以在服务器上执行,所以我可以假装PHP可以在客户端上执行:) – 2011-04-20 19:55:33

+2

如果它们不是完全错误的考虑Node.js ;-) – 2012-01-17 14:32:23

1

我的正则表达式是非常糟糕的,所以我会用一个不太有效的解决方案凑合:P

// The first part is to ensure you can handle both URLs with the http:// and those without 

x = window.location.href.split("http:\/\/") 
x = x[x.length-1]; 
x = x.split("\/")[1]; //Result is in x 
12

非正则表达式。

var link = document.location.href.split('/'); 
alert(link[3]); 
1

这里是快速的方式来获得在Javascript中

var urlPath = window.location.pathname.split("/"); 
if (urlPath.length > 1) { 
    var first_part = urlPath[1]; 
    alert(first_part); 
} 
7

爆炸在JavaScript中的URL可以使用官方rfc2396 regex来完成:

var url = "http://www.domain.com/path/to/something?query#fragment"; 
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/); 

这将会为您提供:

["", "http:", "http", "//www.domain.com", "www.domain.com", "/path/to/something", "?query", "query", "#fragment", "fragment", ""] 

在这里你可以在你的情况下,轻松检索您路径:

var firstPortion = exp[5].split("/")[1] 
相关问题