4

I'm trying to write a function that will remove a query argument from a url in javascript. I think I have it using regex, but I'm not sure if I've missed anything. Also, I can't shake the feeling that there was probably a better way to do this that didn't involve me messing around with regex half the day and running the risk of later finding out that I didn't take some kind of corner case into account.

remove_query_argument = function(url, arg){

    var query_arg_regex;

    // Remove occurences that come after '&' symbols and not the first one after the '?'
    query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig');
    url = url.replace(query_arg_regex, '');

    // remove the instance that the argument to remove is the first one
    query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i');
    url = url.replace(query_arg_regex, function (match, capture) {
        if( capture != '&' ){
            return '';
        }else{
            return '?'
        }

    });

    return url;
}

Does anyone see any problems with this code or would like to suggest a better implementation or way of going about this?

Thanks!

1

2 Answers 2

3

If you have a lot of URL-related operations, you better try this awesome js library https://github.com/medialize/URI.js

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, looks like this would have saved me a ton of time: medialize.github.com/URI.js/docs.html#search-remove
2

Given a percent-encoded URL, the following function will remove field-value pairs from its query string:

var removeQueryFields = function (url) {
    var fields = [].slice.call(arguments, 1).join('|'),
        parts = url.split( new RegExp('[&?](' + fields + ')=[^&]*') ),
        length = parts.length - 1;
    return parts[0] + '?' + (length ? parts[length].slice(1) : '');
}

Some examples:

var string = 'http://server/path/program?f1=v1&f2=v2';
removeQueryFields( string, 'f1' );       // 'http://server/path/program?f2=v2'
removeQueryFields( string, 'f2' );       // 'http://server/path/program?f1=v1'
removeQueryFields( string, 'f1', 'f2' ); // 'http://server/path/program'

2 Comments

This will drop any fragment on the URL when the last parameter is removed.
Because his RegExp is wrong, it wont work when there is an empty value parameter. I used this script and fixed it when realized it did't work: new RegExp('[&?](' + fields + ')=.*[^&].*') )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.