7

我有一个像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

谢谢,迈克尔

4

3 回答 3

19
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 中获取查询字符串值?

于 2012-07-30T18:29:36.243 回答
7

要获取哈希:

location.hash.substr(1); //substr removes the leading #

获取查询字符串

location.search.substr(1); //substr removes the leading ?

[编辑 - 由于您似乎有一个排序查询字符串 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"
于 2012-07-30T18:44:10.787 回答
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
}
于 2012-07-30T18:36:25.650 回答