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

问题描述 投票:0回答:3

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

?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
javascript jquery query-string str-replace
3个回答
1
投票

自定义函数将是:

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

所以可以这样做:

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

1
投票

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

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

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

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

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);
© www.soinside.com 2019 - 2024. All rights reserved.