正则表达式获取/和/之间的URL中的最后一个单词

时间:2012-06-20 16:39:31

标签: javascript

如何获取/和/?

之间URL的URL中的最后一个单词

例如:

http://mywebsite.com/extractMe/test

http://mywebsite.com/extractMe

http://mywebsite.com/settings/extractMe/test

http://mywebsite.com/settings/extractMe

在这里,我希望从网址获取extractMe

4 个答案:

答案 0 :(得分:3)

如果网址一致,为什么不使用:

// Option 1
var url = "http://mywebsite.com/extractMe/test";
var extractedText = url.split("/")[3];

​// Option 2
// If when a trailing slash is present you want to return "test", use this code
var url = "http://mywebsite.com/extractMe/test/";
var urlAry = url.split("/");
var extractedText = urlAry[urlAry.length - 2];

​// Option 3
// If when a trailing slash is present you want to return "extractMe", use this:
var url = "http://mywebsite.com/extractMe/test/";
var urlAry = url.split("/");
var positionModifier = (url.charAt(url.length-1) == "/") ? 3 : 2;    
var extractedText = urlAry[urlAry.length - positionModifier];

这是一个工作小提琴:http://jsfiddle.net/JamesHill/Arj9B/

答案 1 :(得分:1)

最终可以使用/不使用它。)

var url = "http://mywebsite.com/extractMe/test/";    
var m = url.match(/\/([^\/]+)[\/]?$/);

console.log(m[1]);

输出: 测试

答案 2 :(得分:0)

此帐户同时适用于http://mywebsite.com/extractMe/testhttp://mywebsite.com/extractMe/

等网址
function processUrl(url)
{
    var tk = url.split('/');
    var n = tk.length;
    return tk[n-2];
}

<强>编辑。

答案 3 :(得分:0)

正则表达方式:

var str = "http://example.com/extractMe/test";
var match = str.match(/\/([^\/]+)\/[^\/]+$/);

if (match) {
    console.log(match[1]);
}