How to replace url parameter with javascript/jquery?

前端 未结 17 2211
旧时难觅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:38

    I have get best solution to replace the URL parameter.

    Following function will replace room value to 3 in the following URL.

    http://example.com/property/?min=50000&max=60000&room=1&property_type=House

    var newurl = replaceUrlParam('room','3');
    history.pushState(null, null, newurl);
    

    function replaceUrlParam(paramName, paramValue){
        var url = window.location.href;
    
        if (paramValue == null) {
            paramValue = '';
        }
    
        var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
        if (url.search(pattern)>=0) {
            return url.replace(pattern,'$1' + paramValue + '$2');
        }
    
        url = url.replace(/[?#]$/,'');
        return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
    }
    

    Output

    http://example.com/property/?min=50000&max=60000&room=3&property_type=House

    0 讨论(0)
  • 2020-11-28 04:39

    In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api

    var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
    url.searchParams.set("foo", "bar");
    console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
    url.searchParams.set("foo", "ooft");
    console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft
    
    0 讨论(0)
  • 2020-11-28 04:42

    The following solution combines other answers and handles some special cases:

    • The parameter does not exist in the original url
    • The parameter is the only parameter
    • The parameter is first or last
    • The new parameter value is the same as the old
    • The url ends with a ? character
    • \b ensures another parameter ending with paramName won't be matched

    Solution:

    function replaceUrlParam(url, paramName, paramValue)
    {
        if (paramValue == null) {
            paramValue = '';
        }
        var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
        if (url.search(pattern)>=0) {
            return url.replace(pattern,'$1' + paramValue + '$2');
        }
        url = url.replace(/[?#]$/,'');
        return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
    }
    

    Known limitations:

    • Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://stackoverflow.com/a/25214672 if you want to remove the parameter.
    0 讨论(0)
  • 2020-11-28 04:44

    In addition to @stenix, this worked perfectly to me

     url =  window.location.href;
        paramName = 'myparam';
            paramValue = $(this).val();
            var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
            var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
            var n=url.indexOf(paramName);
            alert(n)
            if(n == -1){
                newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
            }
            window.location.href = newUrl;
    

    Here no need to save the "url" variable, just replace in current url

    0 讨论(0)
  • 2020-11-28 04:45

    Wouldn't this be a better solution?

    var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
    var newSrc = 'www.google.com';
    var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');
    

    EDIT:

    added some clarity in code and kept 'src' in the resulting link

    $1 represents first part within the () (i.e) src= and $2 represents the second part within the () (i.e) &, so this indicates you are going to change the value between src and &. More clear, it should be like this:

    src='changed value'& // this is to be replaced with your original url
    

    ADD-ON for replacing all the ocurrences:

    If you have several parameters with the same name, you can append to the regex global flag, like this text.replace(/(src=).*?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.

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