【问题标题】:How to get the hashtag value and ampersand value of a url in Javascript?如何在 Javascript 中获取 url 的标签值和 & 值?
【发布时间】:2012-07-28 11:12:24
【问题描述】:

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

谢谢, 迈克尔

【问题讨论】:

  • @MatthewBlancarte 没有任何捷径可以在 & 号之后获取任何东西,比如我们对哈希标签所拥有的东西,如果没有,那么方法是什么
  • 您是否尝试过我在答案底部给出的链接中接受的方法? stackoverflow.com/questions/901115/… 这将解析查询字符串。如果你在做这个服务器端(例如,PHP/Rails/等),它会简单得多。

标签: javascript jquery url query-string


【解决方案1】:
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.

现在,如果您需要解析查询字符串,我相信您会这样做,请在此处查看:How can I get query string values in JavaScript?

【讨论】:

  • 有没有办法在&之后获取值
  • 这是一个单独的问题 - 请照此发布,或编辑当前问题。 ? 之后的部分(不是 & 是查询字符串 - 您询问了哈希)。
  • @Mike 它会抓取井号标签之后的所有内容,包括井号标签和不带“?”的查询字符串。 :)
  • 假设我只有 www.domain.com&val=1&val=4,我需要得到 &val=1&val=4
  • 我需要什么来获取查询字符串。
【解决方案2】:

这将获得#& 值:

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
}

【讨论】:

  • cannot read property '1' of null 是我在控制台中运行时遇到的错误
  • 这将在没有哈希的任何时候出错,因为假设匹配,而不是检查。
  • 另外,这不会再出错了,因为我添加了if 语句。
  • @AlexW 我认为这种方法可用于从 url 中查找任何内容,而不仅仅是 hashtag,对吧
  • @Mike 正确。您也可以使用此方法找到与号。
【解决方案3】:

获取哈希:

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

获取查询字符串

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

[编辑 - 因为您似乎有一个 sort 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"

【讨论】:

  • 这是因为您将查询字符串与哈希混淆了。您似乎有一种查询字符串-esq 字符串作为哈希的一部分。如果你想提取那个,你需要一些正则表达式,字符串处理。我会编辑答案。
猜你喜欢
  • 2016-06-25
  • 2013-07-23
  • 2018-02-13
  • 2016-05-30
  • 1970-01-01
  • 2013-04-28
  • 2012-11-07
  • 2020-09-18
  • 2021-01-22
相关资源
最近更新 更多