How to replace url parameter with javascript/jquery?

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

    Javascript now give a very useful functionnality to handle url parameters: URLSearchParams

    var searchParams = new URLSearchParams(window.location.search);
    searchParams.set('src','newSrc')
    var newParams = searchParams.toString()
    
    0 讨论(0)
  • 2020-11-28 04:27

    Nowdays that's possible with native JS

    var href = new URL('https://google.com?q=cats');
    href.searchParams.set('q', 'dogs');
    console.log(href.toString()); // https://google.com/?q=dogs
    
    0 讨论(0)
  • 2020-11-28 04:27

    Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:

    /search?searchquery=text and 'query' is provided.
    

    In this case searchquery param value is changed.

    Code:

    function replaceUrlParam(url, paramName, paramValue){
        var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
        var newUrl=url
        if(url.search(pattern)>=0){
            newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
        }
        else{
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
        }
        return newUrl
    }
    
    0 讨论(0)
  • 2020-11-28 04:28

    2020 answer since I was missing the functionality to automatically delete a parameter, so:

    Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 : I combined it with the ability to:

    • automatically delete an URL param if the value if null or '' based on answer https://stackoverflow.com/a/25214672/6284674

    • optionally push the updated URL directly in the window.location bar

    • IE support since it's only using regex and no URLSearchParams

    JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/

    
    function replaceUrlParam(url, paramName, paramValue){
        if(paramValue == null || paramValue == "")
            return url
            .replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?$'), '$1')
            .replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');   
        url = url.replace(/\?$/,'');
        var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
        if(url.search(pattern)>=0){
            return url.replace(pattern,'$1' + paramValue + '$2');
        }
        return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
    }
    
    // Orginal URL (default jsfiddle console URL)
    //https://fiddle.jshell.net/_display/?editor_console=true
    
    console.log(replaceUrlParam(window.location.href,'a','2'));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=2
    
    console.log(replaceUrlParam(window.location.href,'a',''));   
    //https://fiddle.jshell.net/_display/?editor_console=true
    
    console.log(replaceUrlParam(window.location.href,'a',3));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=3
    
    console.log(replaceUrlParam(window.location.href,'a', null));   
    //https://fiddle.jshell.net/_display/?editor_console=true&
    
    //Optionally also update the replaced URL in the window location bar
    //Note: This does not work in JSfiddle, but it does in a normal browser
    function pushUrl(url){
        window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));   
    }
    
    
    pushUrl(replaceUrlParam(window.location.href,'a','2'));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=2
    
    pushUrl(replaceUrlParam(window.location.href,'a',''));   
    //https://fiddle.jshell.net/_display/?editor_console=true
    
    pushUrl(replaceUrlParam(window.location.href,'a',3));   
    //https://fiddle.jshell.net/_display/?editor_console=true&a=3
    
    pushUrl(replaceUrlParam(window.location.href,'a', null));   
    //https://fiddle.jshell.net/_display/?editor_console=true&
    
    
    0 讨论(0)
  • 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);
    };
    
    0 讨论(0)
  • 2020-11-28 04:33

    If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:

    urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);
    

    Example:

    let urlValue = 'www.example.com?a=b&src=test-value&p=q';
    const newValue = 'sucess';
    console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
    // output - www.example.com?a=b&src=sucess&p=q
    
    0 讨论(0)
提交回复
热议问题