简体   繁体   English

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

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

Here's my current code: 这是我当前的代码:

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

When I go to http://example.com/12345/ , then subid equals 12345 . 当我转到http://example.com/12345/subid等于12345

But when I go to http://example.com/12345 , then subid is blank. 但是当我转到http://example.com/12345subid为空白。

How can I make this work with or without the trailing slash? 无论有没有斜杠,我如何使它起作用?

If you consider regex, 如果您考虑使用正则表达式,

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

Test with different cases 在不同情况下进行测试

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);

Try this one. 试试这个。

    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);

So much overkill and code that doesn't work in older browsers in other answers. 在其他答案中,太多的过大杀伤力和代码无法在旧版浏览器中使用。 It's as simple as this: 就这么简单:

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

You can assign the result of match to another variable and add more groupings to the regex if you need to capture other segments, too. 您也可以将match结果分配给另一个变量,并在需要捕获其他段的情况下将更多分组添加到正则表达式中。

if you want to extract last part of string then you can use 如果要提取字符串的最后一部分,则可以使用

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

in case of last '/ first check with .endsWith('/') method and then remove last '/' using 如果是最后一个'/,请首先使用.endsWith('/')方法进行检查,然后使用

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

alternative way is 另一种方法是

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

You can take a benefit of inbuilt function URL 您可以利用内置函数URL

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

The one who are looking for the last segment only can use this function 只寻找最后一个片段的人可以使用此功能

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


console.log(lastSegment);

For old browsers 对于旧的浏览器

// 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