Adding a parameter to the URL with JavaScript

后端 未结 30 2235
刺人心
刺人心 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:56

    Adding to @Vianney's Answer https://stackoverflow.com/a/44160941/6609678

    We can import the Built-in URL module in node as follows

    const { URL } = require('url');
    

    Example:

    Terminal $ node
    > const { URL } = require('url');
    undefined
    > let url = new URL('', 'http://localhost:1989/v3/orders');
    undefined
    > url.href
    'http://localhost:1989/v3/orders'
    > let fetchAll=true, timePeriod = 30, b2b=false;
    undefined
    > url.href
    'http://localhost:1989/v3/orders'
    >  url.searchParams.append('fetchAll', fetchAll);
    undefined
    >  url.searchParams.append('timePeriod', timePeriod);
    undefined
    >  url.searchParams.append('b2b', b2b);
    undefined
    > url.href
    'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
    > url.toString()
    'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
    

    Useful Links:

    https://developer.mozilla.org/en-US/docs/Web/API/URL https://developer.mozilla.org/en/docs/Web/API/URLSearchParams

    0 讨论(0)
  • 2020-11-22 07:57

    If you have a string with url that you want to decorate with a param, you could try this:

    urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
    

    This means that ? will be the prefix of the parameter, but if you already have ? in urlstring, than & will be the prefix.

    I would also recommend to do encodeURI( paramvariable ) if you didn't hardcoded parameter, but it is inside a paramvariable; or if you have funny characters in it.

    See javascript URL Encoding for usage of the encodeURI function.

    0 讨论(0)
  • 2020-11-22 07:58

    This is what I use when it comes to some basic url param additions or updates on the server-side like Node.js.

    CoffeScript:

    ###
        @method addUrlParam Adds parameter to a given url. If the parameter already exists in the url is being replaced.
        @param {string} url
        @param {string} key Parameter's key
        @param {string} value Parameter's value
        @returns {string} new url containing the parameter
    ###
    addUrlParam = (url, key, value) ->
        newParam = key+"="+value
        result = url.replace(new RegExp('(&|\\?)' + key + '=[^\&|#]*'), '$1' + newParam)
        if result is url
            result = if url.indexOf('?') != -1 then url.split('?')[0] + '?' + newParam + '&' + url.split('?')[1]
        else if url.indexOf('#') != -1 then url.split('#')[0] + '?' + newParam + '#' + url.split('#')[1]
        else url + '?' + newParam
        return result

    JavaScript:

    function addUrlParam(url, key, value) {
        var newParam = key+"="+value;
        var result = url.replace(new RegExp("(&|\\?)"+key+"=[^\&|#]*"), '$1' + newParam);
        if (result === url) { 
            result = (url.indexOf("?") != -1 ? url.split("?")[0]+"?"+newParam+"&"+url.split("?")[1] 
               : (url.indexOf("#") != -1 ? url.split("#")[0]+"?"+newParam+"#"+ url.split("#")[1] 
                  : url+'?'+newParam));
        }
        return result;
    }
    
    var url = "http://www.example.com?foo=bar&ciao=3&doom=5#hashme";
    result1.innerHTML = addUrlParam(url, "ciao", "1");
    <p id="result1"></p>

    0 讨论(0)
  • 2020-11-22 07:59

    Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun

    function changeURL(tag)
    {
    if(window.location.href.indexOf("?") > -1) {
        if(window.location.href.indexOf("&"+tag) > -1){
    
            var url = window.location.href.replace("&"+tag,"")+"&"+tag;
        }
        else
        {
            var url = window.location.href+"&"+tag;
        }
    }else{
        if(window.location.href.indexOf("?"+tag) > -1){
    
            var url = window.location.href.replace("?"+tag,"")+"?"+tag;
        }
        else
        {
            var url = window.location.href+"?"+tag;
        }
    }
      window.location = url;
    }
    

    THEN

    changeURL("i=updated");
    
    0 讨论(0)
  • 2020-11-22 08:02

    Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all. Hope this would help.

    function insertParam(key, value) {
            key = escape(key); value = escape(value);
    
            var kvp = document.location.search.substr(1).split('&');
            if (kvp == '') {
                document.location.search = '?' + key + '=' + value;
            }
            else {
    
                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
                document.location.search = kvp.join('&');
            }
        }
    
    0 讨论(0)
  • 2020-11-22 08:02

    Check out https://github.com/derek-watson/jsUri

    Uri and query string manipulation in javascript.

    This project incorporates the excellent parseUri regular expression library by Steven Levithan. You can safely parse URLs of all shapes and sizes, however invalid or hideous.

    0 讨论(0)
提交回复
热议问题