Adding a parameter to the URL with JavaScript

后端 未结 30 2605
刺人心
刺人心 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 08:07

    It handles such URL's:

    • empty
    • doesn't have any parameters
    • already have some parameters
    • have ? at the end, but at the same time doesn't have any parameters

    It doesn't handles such URL's:

    • with fragment identifier (i.e. hash, #)
    • if URL already have required query parameter (then there will be duplicate)

    Works in:

    • Chrome 32+
    • Firefox 26+
    • Safari 7.1+
    function appendQueryParameter(url, name, value) {
        if (url.length === 0) {
            return;
        }
    
        let rawURL = url;
    
        // URL with `?` at the end and without query parameters
        // leads to incorrect result.
        if (rawURL.charAt(rawURL.length - 1) === "?") {
            rawURL = rawURL.slice(0, rawURL.length - 1);
        }
    
        const parsedURL = new URL(rawURL);
        let parameters = parsedURL.search;
    
        parameters += (parameters.length === 0) ? "?" : "&";
        parameters = (parameters + name + "=" + value);
    
        return (parsedURL.origin + parsedURL.pathname + parameters);
    }
    

    Version with ES6 template strings.

    Works in:

    • Chrome 41+
    • Firefox 32+
    • Safari 9.1+
    function appendQueryParameter(url, name, value) {
        if (url.length === 0) {
            return;
        }
    
        let rawURL = url;
    
        // URL with `?` at the end and without query parameters
        // leads to incorrect result.
        if (rawURL.charAt(rawURL.length - 1) === "?") {
            rawURL = rawURL.slice(0, rawURL.length - 1);
        }
    
        const parsedURL = new URL(rawURL);
        let parameters = parsedURL.search;
    
        parameters += (parameters.length === 0) ? "?" : "&";
        parameters = `${parameters}${name}=${value}`;
    
        return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
    }
    

提交回复
热议问题