繁体   English   中英

获取带有或不带有URL斜杠的目录?

[英]Get directory with or without trailing slash of a URL?

这是我当前的代码:

var loc = window.location.pathname;
var str = loc.substring(0, loc.lastIndexOf('/'));
var subid = str.replace("/", "");

当我转到http://example.com/12345/subid等于12345

但是当我转到http://example.com/12345subid为空白。

无论有没有斜杠,我如何使它起作用?

如果您考虑使用正则表达式,

var loc = window.location.pathname;
var subid = loc.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];

在不同情况下进行测试

var url1 = "http://google.com/abc-1";
var url2 = "http://google.com/abc-2/";
var subid1 = url1.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
var subid2 = url2.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
console.log(subid1);
console.log(subid2);

试试这个。

    var loc="http://example.com/12340/";
    if((loc.length-1)==loc.lastIndexOf('/'))
    {

        var newloc=loc.substring(0,loc.length-1);
        var subid=newloc.substring((newloc.lastIndexOf('/')+1),newloc.length);
    }
    else
    {
        var subid=loc.substring((loc.lastIndexOf('/')+1),loc.length);
    }
    console.log("sub is "+subid);

在其他答案中,太多的过大杀伤力和代码无法在旧版浏览器中使用。 就这么简单:

var subid = location.pathname.match(/^\/([^\/]*)/)[1];

您也可以将match结果分配给另一个变量,并在需要捕获其他段的情况下将更多分组添加到正则表达式中。

如果要提取字符串的最后一部分,则可以使用

loc.substring(loc.lastIndexOf('/')).replace('/','');

如果是最后一个'/,请首先使用.endsWith('/')方法进行检查,然后使用

if(loc.endsWith('/')) {
   loc.substring( -1, loc.lastIndexOf('/')).replace('/','');
}

另一种方法是

 loc.split('/').filter( path => !path).pop();

您可以利用内置函数URL

(new URL('http://example.com/12345/')).pathname.replace(/\//g,'') // output 12345
(new URL('http://example.com/12345')).pathname.replace(/\//g,'') // output 12345

只寻找最后一个片段的人可以使用此功能

var allPartsOfURL = 'http://example.com/12345/12/98/567'.split('/');
// handle potential trailing slash
var lastSegment = allPartsOfURL.pop() || allPartsOfURL.pop();  


console.log(lastSegment);

对于旧的浏览器

// create an anchor tag 
const url = document.createElement('a');
// set the href attribute and then use the `pathname`
url.setAttribute('href', 'http://example.com/12345/');
url.pathname.replace(/\//g,''); // output 12345

url.setAttribute('href', 'http://example.com/12345');
url.pathname.replace(/\//g,''); // output 12345

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM