我有一个类似
http://www.example.com/folder/file.html#val=90&type="test"&set="none"&value="reset?setvalue=1&setvalue=45"
的网址
现在我需要获取从 # 开始的 url 部分,我该如何获取它,我尝试使用
window.location.search.substr();
但看起来像是搜索?在一个网址中。有没有办法获取#后面的url值
我如何从 & 符号中获取 URL 的一部分
谢谢, 迈克尔
var hash = window.location.hash;
更多信息请参见:https://developer.mozilla.org/en/DOM/window.location
更新:这将抓取主题标签之后的所有字符,包括任何查询字符串。来自 MOZ 手册:
window.location.hash === the part of the URL that follows the # symbol, including the # symbol.
You can listen for the hashchange event to get notified of changes to the hash in
supporting browsers.
现在,如果您需要解析查询字符串(我相信您会这样做),请在此处查看:如何在 JavaScript 中获取查询字符串值?
获取哈希值:
location.hash.substr(1); //substr removes the leading #
获取查询字符串
location.search.substr(1); //substr removes the leading ?
[编辑 - 由于您似乎有一个排序 query-string-esq 字符串,它实际上是哈希的一部分,因此以下内容将检索它并将其解析为名称/值配对的对象。
var params_tmp = location.hash.substr(1).split('&'),
params = {};
params_tmp.forEach(function(val) {
var splitter = val.split('=');
params[splitter[0]] = splitter[1];
});
console.log(params.set); //"none"
这将获得
#
和 &
值:
var page_url = window.location + ""; // Get window location and convert to string by adding ""
var hash_value = page_url.match("#(.*)"); // Regular expression to match anything in the URL that follows #
var amps; // Create variable amps to hold ampersand array
if(hash_value) // Check whether the search succeeded in finding something after the #
{
amps = (hash_value[1]).split("&"); // Split string into array using "&" as delimiter
alert(amps); // Alert array which will contain value after # at index 0, and values after each & as subsequent indices
}
获取哈希值
window.location.hash
获取哈希值(不带
#
)
window.location.hash.slice(1)