admin管理员组

文章数量:1355754

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
Add a ment  | 

3 Answers 3

Reset to default 4

A 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);

本文标签: javascriptNeatly get query string with comma separated valuesStack Overflow