現在許多的主流網站都將'#'大規模用於重要URL中,我們通過正則表達式和window.location.search獲取參數已經行不通了。
一.'#'號是什么
1.#代表網頁中的一個位置。其后面的字符,就是該位置的標識符。
2.#是用來指導瀏覽器動作的,對服務器端完全無用。所以,HTTP請求中不包括#。
3.在第一個#后面出現的任何字符,都會被瀏覽器解讀為位置標識符。這意味着,這些字符都不會被發送到服務器端。
4.單單改變#后的部分,瀏覽器只會滾動到相應位置,不會重新加載網頁。
5.每一次改變#后的部分,都會在瀏覽器的訪問歷史中增加一個記錄,使用"后退"按鈕,就可以回到上一個位置。
二.如何獲取#號后的字符串
1.window.location.search:獲取當前URL的'?'號開始的字符串
2.window.location.hash:獲取當前URL的'#'后面的字符串
三.js代碼
1.獲取鏈接后的參數(不帶#號)
getQueryString(name) { let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); let r = window.location.search.substr(1).match(reg); if (r != null) return decodeURIComponent(r[2]); return null; }
2.獲取鏈接后的參數(帶#號)
getQueryString(name) { let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); if(window.location.hash.indexOf("?") < 0){ return null; } let r = window.location.hash.split("?")[1].match(reg); if (r != null) return decodeURIComponent(r[2]); return null; }
3.使用方法
console.log('name is ',getQueryString('name'))
(本文來源自 俊俊的小熊餅干 地址:https://www.cnblogs.com/wenjunwei/p/9698379.html)