Delete empty params from query string JS
It's less functional, but you can create a single URLSearchParams
object, then iterate over it and .delete
keys which have an empty value:
const queryString = "paymentMethod=1&fullname=&persona=&companyName=&countryName=&email=&totalCameras=&camerasOwned=&cameraShares=&snapmailCount=&sessionCount=&createdAtDate=&lastLoginAtDate=&telephone=&sort=created_at%7Cdesc&limit=50&page=1"
const params = new URLSearchParams(queryString);
[...params.entries()].forEach(([key, value]) => {
if (!value) {
params.delete(key);
}
});
const cleaned = String(params);
console.log(cleaned);
How to remove empty query params using URLSearchParams?
You can iterate over the key-value pair and delete the keys with null
values:
const x = {
a: 'hello World',
b: '',
c: ''
};
let params = new URLSearchParams(x);
let keysForDel = [];
params.forEach((value, key) => {
if (value == '') {
keysForDel.push(key);
}
});
keysForDel.forEach(key => {
params.delete(key);
});
console.log(params.toString());
How can I remove empty fields from my form in the querystring?
You could use jQuery's submit function to validate/alter your form:
<form method="get" id="form1">
<input type="text" name="aaa" id="aaa" />
<input type="text" name="bbb" id="bbb" />
<input type="submit" value="Go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").submit(function() {
if($("#bbb").val()=="") {
$("#bbb").remove();
}
});
});
</script>
Best way to remove empty query strings from an API request
Considering your params are stored in an object (as you mentioned in your latest edit), you can just remove properties containing empty strings:
const params = { search: "", state_id: 2};
for (const key of Object.keys(params)) { if (params[key] === "") { delete params[key]; }}
console.info(params);
remove all empty values from url
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
How can I delete a query string parameter in JavaScript?
"[&;]?" + 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.
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var prefix = encodeURIComponent(parameter) + '=';
var pars = urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i = pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
}
return url;
}
Related Topics
Multiple Level Nesting in Yaml
Suppresing Output to Console with Ruby
How to Integrate 'Premailer' with Rails
Rails Initializes Extremely Slow on Ruby 1.9.1
Expected #Count to Have Changed by 1, But Was Not Given a Block
Run a Command Line with Custom Environment
Convert Array-Of-Hashes to a Hash-Of-Hashes, Indexed by an Attribute of the Hashes
How to Convert Utf8 Combined Characters into Single Utf8 Characters in Ruby
What Are the Steps Needed to Create and Publish a Rubygem of Your Own
How to Put a Delay on a Loop in Ruby
The Program 'Rails' Can Be Found in the Following Packages - Issue with Some App and Rvm
How to Write Bom Marker to a File in Ruby
Ssl_Connect Syscall Returned=5 Errno=0 State=Sslv2/V3 Read Server Hello A
Ruby: Yield Block from a Block
Programmatically Derive a Regular Expression from a String
Zentest Autotest Not Running Tests