[英]Is there a more succinct way to get the last number in my url?
因此,我目前將兩個變量傳遞到url中,以便在另一頁上使用。 我得到與location.hash的最后一個變量(即#12345)。 然后從URL的另一部分(john%20jacob%202),我需要的只是'2'。 我已經開始工作了,但是覺得必須有一種更簡潔的方法來解決這個問題。 (john%20jacob%202)將始終更改為具有不同的字符串長度。
url: http://localhost/index.html?john%20jacob%202?#12345
<script>
var hashUrl = location.hash.replace("?","");
// function here to use this data
var fullUrl = window.location.href;
var urlSplit = fullUrl.split('?');
var justName = urlSplit[1];
var nameSplit = justName.split('%20');
var justNumber = nameSplit[2];
// function here to use this data
</script>
一個真正快速的單線可能是這樣的:
let url = 'http://localhost/index.html?john%20jacob%202?#12345';
url.split('?')[1].split('').pop();
// returns '2'
怎么樣
decodeURI(window.location.search).replace(/\D/g, '')
由於您的window.location.search
是URI編碼的,因此我們首先對其進行解碼。 然后用數字代替所有不是數字的東西。 對於您的特定URL,它將返回2
編輯為清晰起見 :
您的示例位置http://localhost/index.html?john%20jacob%202?#12345包含幾部分,但有趣的是,在?
之后的部分?
在#
之前。
在Javascript中,可通過window.location.search
獲得此有趣的部分,即查詢字符串(或search
)。 對於您的特定位置, window.location.search
將返回?john%20jacob%202?
。
%20
是URI編碼的空間。 為了對所有URI編碼進行解碼(即刪除),我首先通過encodeURI函數運行search
字符串。 然后,我使用正則表達式將該字符串中不是數字的所有內容替換為空字符串。
正則表達式/\\D/
匹配不是數字的任何字符,並且g
是一個修飾符,指定我要匹配所有內容(不僅僅是在第一次匹配之后停止),結果為2
。
如果您知道自己一直在標簽后面,則可以替換所有內容,直到“#”
url.replace(/^.+#/, '');
另外,此正則表達式將匹配URL中的最后一個數字:
url.match(/(?<=\D)\d+$/);
//(positive look behind for any non-digit) one more digits until the end of the string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.