2011-10-06 29 views
2

我有一对夫妇的URL的,我需要得到的URI获取使用Javascript

最后一部分的特定部分。如果我有网址www.test.co/index.php/government-printer-sales.html我只需要从获得government一个URL的特定部分网址。所有网址都在相同的结构,所以如果我有www.test.co/index.php/management-fees.html我需要获得management

我尝试以下

var str = document.URL.split('/'); 
var type = str[5].split('-',1); 

这给了我一些成绩的话,但我敢肯定有一个更好的办法。如果有反正我可以从eiter的mootools获得此或只是简单的JavaScript

+0

这是真正的网址吗?如果只有2个斜杠,那么为什么要访问分割字符串的索引“5”? – pimvdb

+0

@pimvdb - 只是例子,可以有更多的两个破折号 – Roland

回答

3

您可以使用正则表达式的最后一个斜杠之后和第一个破折号前拉出字符串:

var regex = /\/([^/\-]+)[^/]*$/; 
var matches = regex.exec('www.test.co/index.php/government-printer-sales.html'); 
var type = matches[1]; // government 
3

你可以看看here然后here,然后检查该代码:

var myString = "www.test.co/index.php/government-printer-sales.html"; 
var myRegexp = /(www.test.co\/index.php\/)(\w+)-(.)*/g; 
var match = myRegexp.exec(myString); 
alert(match); 
3

接头是一个负数通过作为第一个参数将创建与来自所述阵列的末端计数元素的新阵列的巨大作用。

document.URL 
> "http://stackoverflow.com/questions/7671441/getting-a-specific-part-of-a-url-using-javascript" 

document.URL.split('/').splice(-1)[0].split('-')[0] 
> "getting" 

这类似于Python的列表拼接LST [: - 1]

2

试试这个:

var type = window.location.pathname.match(/index.php\/([^-]+)(?:-)/)[1]; 

它搜索以下index.php/排除连字符的任何字符,但随后单连字符并获取之间的值。