Remove request argument from url in javascript

I am trying to write a function that will remove a request argument from a url in javascript. I think I use regex, but I'm not sure if I missed something. In addition, I cannot shake the feeling that there was probably the best way to do this, which did not include me all the time with regular expression, and risking later to find out that I did not take any angle case.

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 a way to do this?

Thanks!

+4
source share
2 answers

If you have a lot of operations with URLs, you better try this wonderful js library https://github.com/medialize/URI.js

+3
source

Given URL percent-encoded , the following function will remove the pairs of field values ​​from the 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
source

Source: https://habr.com/ru/post/1388785/


All Articles