Javascript 如何在JS中的URL中获取#hash值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11920697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get #hash value in a URL in JS
提问by Akshat Mittal
For example, I have a URL as :
例如,我有一个 URL 为:
I want a js code to return just value2x
.
I tried location.hash.split('=')[1]
but that results the first hash value like if url is
我想要一个 js 代码只返回value2x
. 我试过了,location.hash.split('=')[1]
但结果是第一个哈希值,就像 url 是
It returns fdg&hash
.
I want just the value of hash
.
它返回fdg&hash
。我只想要hash
.
NO jQuery Please.
请不要使用jQuery。
Thanks for the help in advance.
我在这里先向您的帮助表示感谢。
回答by xdazz
function getHashValue(key) {
var matches = location.hash.match(new RegExp(key+'=([^&]*)'));
return matches ? matches[1] : null;
}
// usage
var hash = getHashValue('hash');
回答by Musa
How about
怎么样
location.hash.split('hash=')[1].split('&')[0]
This will split the hash at hash=
and take the value after hash= and before any other argument .
这将拆分哈希 athash=
并在 hash= 之后和任何其他参数之前取值。
回答by nishantkyal
The URLSearchParams class can be reused for this purpose.
URLSearchParams 类可以重用于此目的。
var urlParams = new URLSearchParams(window.location.hash.replace("#","?"));
var hash = urlParams.get('hash');
回答by RameshVel
If you are doing extensive url manipulations, then you shoud check out JQuery URL plugin.
如果您正在进行大量的 url 操作,那么您应该查看JQuery URL 插件。
To access the params in url hashes
访问 url 哈希中的参数
$.url('http://www.google.com/#hfh=fdg&hash=value2x').fparam('hash');
or if its current url
或者如果它的当前网址
$.url().fparam('hash');
Hope it helps
希望能帮助到你
回答by abuduba
location.parseHash = function(){
var hash = (this.hash ||'').replace(/^#/,'').split('&'),
parsed = {};
for(var i =0,el;i<hash.length; i++ ){
el=hash[i].split('=')
parsed[el[0]] = el[1];
}
return parsed;
};
var obj= location.parseHash();
obj.hash; //fdg
obj.hfh; //value2x
回答by Gumbo
Split on &
and then on =
:
拆分&
然后拆分=
:
pairs = location.hash.substr(1).split('&').map(function(pair) {
var kv = pair.split('=', 2);
return [decodeURIComponent(kv[0]), kv.length === 2 ? decodeURIComponent(kv[1]) : null];
})
Here pairs
will be an array of arrays with the key at 0
and the value at 1
:
这里pairs
将是一个数组数组,其键为 at 0
,值为 at 1
:
[["hfh","fdg"],["hash","value2x"]]