我有几个URL需要获取URI的最后部分的特定部分
如果我有网址www.test.co/index.php/government-printer-sales.html
,我只需要从网址获取government
。所有网址都是相同的结构,所以如果我有www.test.co/index.php/management-fees.html
我需要获取单词management
我尝试了以下
var str = document.URL.split('/');
var type = str[5].split('-',1);
这给了我一些结果,但我确信有更好的方法。无论如何,我可以从eiter mootools或只是简单的javascript
获得这个答案 0 :(得分:3)
您可以使用正则表达式在最后一个斜杠之后和第一个破折号之前拉出字符串:
var regex = /\/([^/\-]+)[^/]*$/;
var matches = regex.exec('www.test.co/index.php/government-printer-sales.html');
var type = matches[1]; // government
答案 1 :(得分:3)
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);
答案 2 :(得分:3)
Splice是一个传递负数的好函数,因为第一个参数将创建一个新数组,其元素从数组末尾开始计算。
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]
答案 3 :(得分:2)
试试这个:
var type = window.location.pathname.match(/index.php\/([^-]+)(?:-)/)[1];
它搜索index.php/
后的任何字符,不包括连字符,但后面跟一个连字符,并在其间取值。