0

我有以下字符串

w[]=18&w[]=2&w[]=2[]=2

我想创建一个 jQuery 函数,让它像这样用逗号分隔:

18,2,2,2
4

3 回答 3

0

采用正则表达式方式,假设示例中的非数字键和数值,我将match()直接使用所有数字。这将返回一个数组,其中包含字符串中所有匹配的数字(不是数字):

var query_string  = 'w[]=18&w[]=2&w[]=2[]=2';
var numbers_array = query_string.match(/\d{1,}/g);

如果您随后需要 CSV 字符串,则可以使用分隔符join()将数组值:,

var numbers_csv = numbers_array.join(',');
于 2013-01-15T13:16:55.930 回答
0

您可以使用String#replace与任何非数字匹配的正则表达式,并删除前导逗号:

var str = "w[]=18&w[]=2&w[]=2[]=2";
str = str.replace(/\D+/g, ',').substring(1);

实例| 资源

于 2013-01-15T13:05:54.830 回答
0

UPDATE: It is much easier to just use substring() and split():

var myArray = str.substring(4).split("&w[]=");

(Assuming that the missing &w is a typo!)

  • substring(4) thows away the first for characters: w[]=
  • split() splits the string into elements using &w[]= as separation string.


Old solution:

Just find the w[]= occurrences and replace the occurrences with a , using the replace() function

var str="w[]=18&w[]=2&w[]=2[]=2";
var fixedStr=str.replace(/\&/g,",").replace(/\w?\[\]\=/g,"");

To convert the string into an array (I suppose you mean 'array' when you say 'list'), you need to split() it at the ,s:

var myArray = fixedStr.split(",");
于 2013-01-15T13:07:05.483 回答