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

?search=%E6%F8%E5

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

æøå

(人物是挪威人)。

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


当前回答

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

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

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

你不应该使用jQuery来做这样的事情! 现代的方法是通过包管理器(如Bower)使用小型可重用模块。

我创建了一个小模块,可以将查询字符串解析为对象。像这样使用它:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå

以下是我从这里的评论中创建的内容,以及修复没有提到的错误(例如实际返回null,而不是'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}