Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex splitting words in a comma separated string

I am trying to split a comma separated string using regex.

var a = 'hi,mr.007,bond,12:25PM'; //there are no white spaces between commas
var b = /(\S+?),(?=\S|$)/g;
b.exec(a); // does not catch the last item.

Any suggestion to catch all the items.

like image 469
kurro Avatar asked Dec 01 '22 21:12

kurro


1 Answers

Use a negated character class:

/([^,]+)/g

will match groups of non-commas.

< a = 'hi,mr.007,bond,12:25PM'
> "hi,mr.007,bond,12:25PM"
< b=/([^,]+)/g
> /([^,]+)/g
< a.match(b)
> ["hi", "mr.007", "bond", "12:25PM"]
like image 104
Reinstate Monica -- notmaynard Avatar answered Dec 11 '22 00:12

Reinstate Monica -- notmaynard