Search and replace specific query string parameter value in javascript

后端 未结 6 1592
无人及你
无人及你 2020-12-23 20:07

I have a string which is something like this :

a_href= \"www.google.com/test_ref=abc\";

I need to search for test_ref=abc in thisabove stri

6条回答
  •  一整个雨季
    2020-12-23 20:45

    I know this is a bit dirty code but I've achieved what I was looking for. It replaces the given query string or adds new one if it doesn't exist yet.

    function updateUrlParameter(url, param, value) {
    
        var index = url.indexOf("?");
    
        if (index > 0) {
    
            var u = url.substring(index + 1).split("&");
    
            var params = new Array(u.length);
    
            var p;
            var found = false;
    
            for (var i = 0; i < u.length; i++) {
                params[i] = u[i].split("=");
                if (params[i][0] === param) {
                    params[i][1] = value;
                    found = true;
                }
            }
    
            if (!found) {
                params.push(new Array(2));
                params[params.length - 1][0] = param;
                params[params.length - 1][1] = value;
            }
    
            var res = url.substring(0, index + 1) + params[0][0] + "=" + params[0][1];
            for (var i = 1; i < params.length; i++) {
                res += "&" + params[i][0] + "=" + params[i][1];
            }
            return res;
    
        } else {
            return url + "?" + param + "=" + value;
        }
    
    }
    

    It will work when given regular URL addresses like:

    updateUrlParameter('https://www.example.com/some.aspx?mid=1&id=2','id','5');
    updateUrlParameter('https://www.example.com/?mid=1&id=2','id','5');
    updateUrlParameter('https://www.example.com/some.aspx','id','5');
    

    Please note It will NOT work only if any of the query string parameter name or value contains "=" and/or "&" chars. It will work just fine behind that.

提交回复
热议问题