Adrian
Adrian

Reputation: 523

Javascript - remove or set another value to URL parameter

I need a function to enable/disable viewport by clicking a button.

So I'm using URL parameters to add &viewport=1 like that I can add/remove meta name="viewport" and reloading the page after that.

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var $viewport = getParameterByName('viewport'),
    $url = window.location.href;
function checkViewport($btn){
    if($viewport === '1') {
        $('head meta[name=viewport]').remove();
        // here I need to change or remove the param from URL
        // tried with $url=$url.replace - not working :(
    } else if (typeof $viewport === 'undefined' || $viewport === null || $viewport === '') {
        $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">');
        if ($url.indexOf('?') > -1){
           $url += '&viewport=1'
        } else {
           $url += '?viewport=1'
        }
    }
    window.history.replaceState(null, null, $url);
    if($btn){
        window.location.href = $url;
    }
}

Can anyone Help me, please?

Thanks.

Upvotes: 1

Views: 343

Answers (1)

Bayrock
Bayrock

Reputation: 26

This provides the result you want for me:

var $url = "http://example.com?viewport=1";
console.log($url); //http://example.com?viewport=1

$url = $url.replace(/[&?]viewport=1/g, "");
console.log($url); //http://example.com

Upvotes: 1

Related Questions