[英]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/12345
, subid
為空白。
無論有沒有斜杠,我如何使它起作用?
如果您考慮使用正則表達式,
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.