Split string by commas only

Let’s suggest I have the following string:
let cssValue = '20px, 40px'

I wish to get the following array after splitting:
cssValue.split(regex); // ['20px', '40px']

But if the string doesn’t contain commas (spaces only, i.e. 20px 40px) the result should be ['20px 40px']

My regex [^a-zA-Z0-9)]+ doesn’t consider comma. With this regex I’m getting ['20px', '40px'] regardless of whether the string contains comma or not. How can I resolve it?

>Solution :

You could split by comma and possible whitespace directly.

const split = s => s.split(/,\s*/);

console.log(split('20px, 40px'));
console.log(split('20px 40px'));

Leave a Reply