I have the following string
w[]=18&w[]=2&w[]=2[]=2
I want to create a jQuery function to make it comma separated like that:
18,2,2,2
You can use String#replace
with a regular expression matching any non-digit, and remove the leading comma:
var str = "w[]=18&w[]=2&w[]=2[]=2";
str = str.replace(/\D+/g, ',').substring(1);
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(",");
Going the regular expression way, assuming non-numeric keys and numeric values as in the example, I would match()
all numbers directly. This would return an array containing all numbers matches (not digits) in the string:
var query_string = 'w[]=18&w[]=2&w[]=2[]=2';
var numbers_array = query_string.match(/\d{1,}/g);
If you then need a CSV string, you can then join()
the array values with a ,
separator:
var numbers_csv = numbers_array.join(',');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.