I'm trying to get a query string that looks like:
?focuses=coding,robotics,electronics&format=clp,hlp
// or this
?focuses=coding,robotics,electronics
// or this
?focuses=coding&format=clp
I have been working on this:
// formats = ['hlp', 'clp'], focuses = ['coding', 'robotics']
var query = jQuery.param({formats, focuses});
query = query.replace(/%5B%5D/g, '');
query = query.replace(/(?!^)&formats=/g, ',');
query = query.replace(/(?!^)$focuses=/g, ',');
But I somehow keep ending up with:
?formats=hlp,clp,coding,robotics,electronics
I'm trying to get a query string that looks like:
?focuses=coding,robotics,electronics&format=clp,hlp
// or this
?focuses=coding,robotics,electronics
// or this
?focuses=coding&format=clp
I have been working on this:
// formats = ['hlp', 'clp'], focuses = ['coding', 'robotics']
var query = jQuery.param({formats, focuses});
query = query.replace(/%5B%5D/g, '');
query = query.replace(/(?!^)&formats=/g, ',');
query = query.replace(/(?!^)$focuses=/g, ',');
But I somehow keep ending up with:
?formats=hlp,clp,coding,robotics,electronics
Share
Improve this question
asked Dec 30, 2017 at 13:05
rabbittrabbitt
2,5988 gold badges28 silver badges41 bronze badges
3 Answers
Reset to default 4A custom function would be:
function query(args){
return "?" + Object.entries(args).map(([key, value]) => {
return key +"="+ value;
}).join("&");
}
So one can do:
query({
focuses:["what", "ever"],
a:"property"
});
Get your objects into the form you want before passing them off to jQuery:
jQuery.param({
formats: formats.join(','),
focuses: focuses.join(',')
});
This still encodes the mas as %2C
(which is valid), but if you really want to use literal mas, you can replace them afterward:
jQuery.param({
formats: formats.join(','),
focuses: focuses.join(',')
}).replace(/%2C/g, ',');
You can do like this way. If you do not require a reusable function getQueryString
then you can move that code outside of that function where you need.
var formats = ['hlp', 'clp'], focuses = ['coding', 'robotics','electronics'];
function getQueryString(formats, focuses){
var formatsString = formats.toString();
var focusesString = focuses.toString();
var finalString = "?focuses="+focusesString+"&format="+formatsString;
return finalString;
}
var result = getQueryString(formats, focuses);
console.log(result);