[英]Get last part of url with / at the end
我正在嘗試獲取此網址的最后一部分:
http://webserver/Foo/login/
我寫的代碼:
var location = window.location.href.split('/').pop();
將返回一個空字符串'因為/
什么都沒有。 我需要至少獲得前一部分,所以在這種情況下,登錄。
我怎樣才能做到這一點?
使用String.replace()
(用於替換字符串末尾的可能/
)和String.split()
函數的解決方案:
var url = 'http://webserver/Foo/login/', last_section = url.replace(/\\/+$/, '').split('/').pop(); console.log(last_section);
const getLastPartURL = url => { const parts = url.split('/'); const length = parts.length; return parts[length - 1] == '' ? parts[length - 2] : parts[length - 1] } console.log(getLastPartURL('http://webserver/Foo/login/')) console.log(getLastPartURL('http://webserver/Foo/login')) console.log(getLastPartURL('http://webserver/Foo/')) console.log(getLastPartURL('http://webserver/Foo'))
這應該做的伎倆:
location.pathname.match(/[^/]*(?=\/*$)/)[0]
說明:
Location.pathname
是一個字符串,包含一個首字母'/'
后跟URL的路徑 。 String.prototype.match(regexp)
返回匹配數組。 [^/]*
匹配除斜線之外的任何東西 ,並且零次或多次 。 (?=\\/*$)
在字符串末尾匹配斜杠零次或多次, 而不包括它 。 [0]
檢索它。 例:
對於所有這些URL,輸出是login
:
http://webserver/Foo/login
http://webserver/Foo/login/
http://webserver/Foo/login//
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.