我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。
?search=%E6%F8%E5
URL参数的值,当解码时,应该是:
æøå
(人物是挪威人)。
我没有访问服务器的权限,所以我不能在上面修改任何东西。
我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。
?search=%E6%F8%E5
URL参数的值,当解码时,应该是:
æøå
(人物是挪威人)。
我没有访问服务器的权限,所以我不能在上面修改任何东西。
当前回答
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
其他回答
jQuery代码片段,以获取动态变量存储在url作为参数,并将它们存储为JavaScript变量,以供您的脚本使用:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
这里有很多有bug的代码,正则表达式解决方案非常慢。我发现了一个解决方案,比正则表达式对应的工作速度快20倍,而且非常简单:
/*
* @param string parameter to return the value of.
* @return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex并不是最重要的解决方案,对于这类问题,简单的字符串操作可以更有效地工作。代码源。
根据999的回答:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
变化:
decodeURI()被decodeURIComponent()取代 (?|&]被添加在regexp的开头
这可能会有所帮助。
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>
需要添加参数i,使其不区分大小写:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}