Adding a parameter to the URL with JavaScript

后端 未结 30 2707
刺人心
刺人心 2020-11-22 07:33

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

30条回答
  •  我寻月下人不归
    2020-11-22 07:52

    Ok here I compare Two functions, one made by myself (regExp) and another one made by (annakata).

    Split array:

    function insertParam(key, value)
    {
        key = escape(key); value = escape(value);
    
        var kvp = document.location.search.substr(1).split('&');
    
        var i=kvp.length; var x; while(i--) 
        {
            x = kvp[i].split('=');
    
            if (x[0]==key)
            {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
            }
        }
    
        if(i<0) {kvp[kvp.length] = [key,value].join('=');}
    
        //this will reload the page, it's likely better to store this until finished
        return "&"+kvp.join('&'); 
    }
    

    Regexp method:

    function addParameter(param, value)
    {
        var regexp = new RegExp("(\\?|\\&)" + param + "\\=([^\\&]*)(\\&|$)");
        if (regexp.test(document.location.search)) 
            return (document.location.search.toString().replace(regexp, function(a, b, c, d)
            {
                    return (b + param + "=" + value + d);
            }));
        else 
            return document.location.search+ param + "=" + value;
    }
    

    Testing case:

    time1=(new Date).getTime();
    for (var i=0;i<10000;i++)
    {
    addParameter("test","test");
    }
    time2=(new Date).getTime();
    for (var i=0;i<10000;i++)
    {
    insertParam("test","test");
    }
    
    time3=(new Date).getTime();
    
    console.log((time2-time1)+" "+(time3-time2));
    

    It seems that even with simplest solution (when regexp use only test and do not enter .replace function) it is still slower than spliting... Well. Regexp is kinda slow but... uhh...

提交回复
热议问题