Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  103] [ 6]  / answers: 1 / hits: 104674  / 12 Years ago, thu, july 12, 2012, 12:00:00

I'm looking for [a, b, c, d, e, f, g, h]to turn into an array of 6 elements: a, b, c, d,e,f, g, h. I'm trying to do this through Javascript. This is what I have so far:



str = str.split(/,+|[^]+/g); 


But right now it's splitting out everything that's in the double-quotes, which is incorrect.



Edit: Okay sorry I worded this question really poorly. I'm being given a string not an array.



var str = 'a, b, c, d, e, f, g, h';


And I want to turn that into an array using something like the split function.


More From » regex

 Answers
0

Here's what I would do.


var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",s]+)(?=s*,|s*$)/g);

enter
/* will match:


    (
".*?" double quotes + anything but double quotes + double quotes
| OR
[^",s]+ 1 or more characters excl. double quotes, comma or spaces of any kind
)
(?= FOLLOWED BY
s*, 0 or more empty spaces and a comma
| OR
s*$ 0 or more empty spaces and nothing else (end of string)
)

*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);

[#84298] Wednesday, July 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samarab

Total Points: 620
Total Questions: 95
Total Answers: 89

Location: Bonaire
Member since Wed, May 11, 2022
2 Years ago
;