使用Javascript从url参数获取变量 [英] Get a variable from url parameter using Javascript
问题描述
我正在尝试使用javascript获取网址值,到目前为止,我只能获得纯数字,而不是字母或字母的混合数字。我找不到任何一个函数的工作示例,它允许检索带有字母的数字,只是数字。我没有使用任何非字母数字字符。我想要传递的示例值是42p316041610751874cm83p2306600132141。
I am trying to get a url value using javascript, so far I can only get pure numbers, not mixed numbers with letters or just letters. I can't find any working examples of a function that allows for numbers with letters to be retrieved, just numbers. I am not using any non alphanumeric characters. An example value that I am trying to pass is "42p316041610751874cm83p2306600132141".
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var first = getUrlVars()["test"];
任何帮助都会很棒。谢谢。
Any help would be great. Thanks.
推荐答案
以下是上述两个答案的精简版本:
Here is a condensed version of two of the answers above :
function gup (name) {
name = RegExp ('[?&]' + name.replace (/([[\]])/, '\\$1') + '=([^&#]*)');
return (window.location.href.match (name) || ['', ''])[1];
}
更容易输入,更容易处理,恕我直言更容易阅读。 YMMV
Easier to type, easier on processing and, IMHO easier to read. YMMV
这篇关于使用Javascript从url参数获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!