Get escaped URL parameter

后端 未结 19 2684
小蘑菇
小蘑菇 2020-11-21 13:41

I\'m looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: \"malformed URI sequence\". If there is

19条回答
  •  我在风中等你
    2020-11-21 13:53

    There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:

        /*
        *   @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 is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.

提交回复
热议问题