Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading