我有以下字符串
w[]=18&w[]=2&w[]=2[]=2
我想创建一个 jQuery 函数,让它像这样用逗号分隔:
18,2,2,2
采用正则表达式方式,假设示例中的非数字键和数值,我将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(',');
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.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(",");