views:

2372

answers:

2

Is there better way to delete a parameter from a query string in a URL string in standard JavaScript other than by using a regular expression?

Here's what I've come up with so far which seems to work in my tests, but I don't like to reinvent querystring parsing!

function RemoveParameterFromUrl( url, parameter ) {

    if( typeof parameter == "undefined" || parameter == null || parameter == "" ) throw new Error( "parameter is required" );

    url = url.replace( new RegExp( "\\b" + parameter + "=[^&;]+[&;]?", "gi" ), "" ); "$1" );

    // remove any leftover crud
    url = url.replace( /[&;]$/, "" );

    return url;
}
+2  A: 
"[&;]?" + parameter + "=[^&;]+"

Seems dangerous because it parameter ‘bar’ would match:

?a=b&foobar=c

Also it would fail if parameter contained any characters that are special in RegExp, such as ‘.’. And it's not a global regex, so it would only remove one instance of the parameter.

I wouldn't use a simple RegExp for this, I'd parse the parameters in and lose the ones you don't want.

var urlparts= url.split('?');   # prefer to use l.search if you have a location/link object
if (urlparts.length>=2) {

    var prefix= encodeURIComponent(parameter)+'=';
    var pars= urlparts[1].split(/[&;]/g);
    for (var i= pars.length; i-->0;)               # reverse iteration as may be destructive
        if (pars[i].lastIndexOf(prefix, 0)!==-1)   # idiom for string.startsWith
            pars.splice(i, 1);
    url= urlparts[0]+'?'+pars.join('&');
}
bobince
Good point about the bar matching the foobar. I've updated my original regex to require a ? or a [] at the start. Also reading over your solution to consider it...
Matthew Lock
and added "g" to make the replacement global ;)
Matthew Lock
A: 

If you're into jQuery, there are some good query string manipulation plugins:

Damovisa