如何获取/和/?
之间URL的URL中的最后一个单词例如:
http://mywebsite.com/extractMe/test
http://mywebsite.com/extractMe
http://mywebsite.com/settings/extractMe/test
http://mywebsite.com/settings/extractMe
在这里,我希望从网址获取extractMe
。
答案 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/test
和http://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]);
}