How to replace url parameter with javascript/jquery?

前端 未结 17 2390
旧时难觅i
旧时难觅i 2020-11-28 04:06

I\'ve been looking for an efficient way to do this but haven\'t been able to find it, basically what I need is that given this url for example:

http://localh         


        
17条回答
  •  悲哀的现实
    2020-11-28 04:30

    try this

    var updateQueryStringParam = function (key, value) {
    
        var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
            urlQueryString = document.location.search,
            newParam = key + '=' + value,
            params = '?' + newParam;
    
        // If the "search" string exists, then build params from it
        if (urlQueryString) {
            var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
            var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
    
            if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
                params = urlQueryString.replace(removeRegex, "$1");
                params = params.replace( /[&;]$/, "" );
    
            } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
                params = urlQueryString.replace(updateRegex, "$1" + newParam);
    
            } else { // Otherwise, add it to end of query string
                params = urlQueryString + '&' + newParam;
            }
        }
    
        // no parameter was set so we don't need the question mark
        params = params == '?' ? '' : params;
    
        window.history.replaceState({}, "", baseUrl + params);
    };
    

提交回复
热议问题