簡體   English   中英

最后使用/獲取網址的最后一部分

[英]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]

說明:

例:

對於所有這些URL,輸出是login

  • http://webserver/Foo/login
  • http://webserver/Foo/login/
  • http://webserver/Foo/login//

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM