我有一个像http://www.example.com/folder/file.html#val=90&type="test"&set="none"&value="reset?setvalue=1&setvalue=45"
现在我需要从#开始获取url的一部分,我如何得到它,我尝试使用window.location.search.substr();
但看起来像搜索?在网址中。有没有一种方法可以在#
我如何从&符号中获取部分网址?
谢谢, 迈克尔
答案 0 :(得分:14)
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.
现在,如果您需要PARSE查询字符串,我相信您这样做,请在此处查看:How can I get query string values in JavaScript?
答案 1 :(得分:6)
抓住哈希:
location.hash.substr(1); //substr removes the leading #
获取查询字符串
location.search.substr(1); //substr removes the leading ?
[编辑 - 因为你似乎有一个sort-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"
答案 2 :(得分:0)
这将获得#
和&
值:
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
}