我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。

?search=%E6%F8%E5

URL参数的值,当解码时,应该是:

æøå

(人物是挪威人)。

我没有访问服务器的权限,所以我不能在上面修改任何东西。


当前回答

需要添加参数i,使其不区分大小写:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }

其他回答

这里有很多有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的开头

以防你们有localhost/index。xsp这样的url ?A =1#一些东西,你需要得到参数而不是哈希值。

var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        anchor = hash[1].split('#');
        vars.push(anchor[0]);
        vars[hash[0]] = anchor[0];
    }
}

例如,返回任意参数变量值的函数。

function GetURLParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

这就是你如何使用这个函数假设URL是,

“http://example.com/?technology=jquery&blog=jquerybyexample”。

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');

所以在上面的代码变量"tech"将有"jQuery"作为值和"blog"变量的将是" querybyexample"。

$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href); 
  return (results !== null) ? results[1] : 0;
}

$.urlParam("key");