整齐地获取带逗号分隔值的查询字符串

时间:2017-12-30 13:05:57

标签: javascript jquery query-string str-replace

我正在尝试获取一个类似于以下内容的查询字符串:

?focuses=coding,robotics,electronics&format=clp,hlp
// or this
?focuses=coding,robotics,electronics
// or this
?focuses=coding&format=clp

我一直在努力:

// 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, ',');

但我不知怎的最后:

?formats=hlp,clp,coding,robotics,electronics

3 个答案:

答案 0 :(得分:1)

自定义功能将是:

 function query(args){
   return "?" + Object.entries(args).map(([key, value]) => {
     return key +"="+ value;
  }).join("&");
}

所以可以这样做:

 query({
  focuses:["what", "ever"],
  a:"property"
});

答案 1 :(得分:1)

在将对象传递给jQuery之前,将对象转换为所需的形式:

jQuery.param({
  formats: formats.join(','),
  focuses: focuses.join(',')
});

这仍然将逗号编码为%2C(这是有效的),但如果您真的想使用文字逗号,则可以在以后替换它们:

jQuery.param({
  formats: formats.join(','),
  focuses: focuses.join(',')
}).replace(/%2C/g, ',');

答案 2 :(得分:0)

你可以这样做。如果您不需要可重复使用的函数getQueryString,那么您可以将该代码移到您需要的函数之外。



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