如何在JavaScript中获取URL的哈希标记值和和号值?

7

我有一个像这样的url: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值?

我如何从&符号获取url的某个部分?

谢谢, 迈克尔


@MatthewBlancarte 有没有获取“&”后面任何内容的快捷方式,就像我们对哈希标签所做的那样,如果没有,那么应该采取什么方法? - Mike
你尝试过我在答案底部提供的链接中所列的标准方法了吗?https://dev59.com/nHNA5IYBdhLWcg3wmfAa 那个方法会解析查询字符串。如果你是在服务器端完成这个任务(例如PHP/Rails等),那么很简单。 - Matthew Blancarte
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中获取查询字符串的值?


有没有办法在 & 后获取一个值? - Mike
那是一个单独的问题 - 请将其作为单独的帖子发布,或编辑当前问题。问号后面的部分(不是&)是查询字符串 - 您询问了哈希值。 - Mitya
我只需要获取查询字符串,我需要什么? - Mike
@Mike,希望你没有一个查询字符串有相同的键,如val和val。:)请检查我的更新答案。在底部有一个链接,说明如何解析js中的查询字符串。 - Matthew Blancarte
显示剩余6条评论

7

获取哈希值的方法:

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

抓取查询字符串
location.search.substr(1); //substr removes the leading ?
< p >【编辑】由于您似乎有一个类似查询字符串的字符串实际上是哈希的一部分,因此以下内容将检索并解析它为名称/值对的对象。

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"

这是因为您将查询字符串与哈希值混淆了。您似乎在哈希值中包含了一种类似于查询字符串的字符串。如果您想要提取那个,您需要使用一些正则表达式和字符串处理。我会编辑答案。 - Mitya

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
}

当我在控制台中运行此代码时,出现了“无法读取null的属性'1'”的错误。 - Mike
1
每当没有哈希时,都会出现错误,因为假定有匹配,而不是检查。 - Mitya
此外,这个错误不会再出现了,因为我添加了 if 语句。 - Alex W
@AlexW 我认为这种方法可以用来从URL中找到任何东西,不仅仅是标签。对吗? - Mike
@Mike 正确。你也可以用这个方法找到&符号。 - Alex W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接