我的网址看起来像这样
stackoverflow.com/questions/ask/format/return
我需要从上面的URL中仅获取
format/return
。我可以将完整的URL分配给一个变量。目前我正在使用split
进行操作。url.split("/")[4]
url.split("/")[5]
而且这不是通用的。有什么更好的方法来实现这个?
我的网址看起来像这样
stackoverflow.com/questions/ask/format/return
format/return
。我可以将完整的URL分配给一个变量。目前我正在使用split
进行操作。url.split("/")[4]
url.split("/")[5]
只需使用长度即可帮助您从末尾进行索引:
var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]
一种基因解决方案,
Var URL = url.split("/");
//
Last = URL[URL.length-1];
// 返回
LastBefore = URL[URL.length-1];
//format
url = "stackoverflow.com/questions/ask/format/return"
URL = url.split("/");
console.log(URL[URL.length-1]) // return
console.log(URL[URL.length-2]) //format
let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
/.*\/(.*\/.*)/
来精确提取你想要的内容。str.match(/.*\/(.*\/.*)/).pop()
var str = "stackoverflow.com/questions/ask/format/return",
res = str.match(/.*\/(.*\/.*)/).pop();
console.log(res);
?foo=bar
),它也能正常工作。
const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");