Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to split a comma separated css class names string into array

I need to split a CSS class names string into array of CSS class names in JavaScript. All the below strings should produce the same array.

'lmn-button,lmn-button-primary' => ['lmn-button', 'lmn-button-primary']

'lmn-button, lmn-button-primary' => ['lmn-button', 'lmn-button-primary'] // Note the space after comma

'lmn-button ,lmn-button-primary' => ['lmn-button', 'lmn-button-primary'] // Note the space before comma

'  lmn-button ,lmn-button-primary' => ['lmn-button', 'lmn-button-primary'] // Note the space at start

'lmn-button ,lmn-button-primary  ' => ['lmn-button', 'lmn-button-primary'] // Note the space at end

Currently I'm using code to do that,

cssClassesString.split(',').map(cssClass => cssClass.trim());

But I believe regex would be a better solution that this right?

I got this regex by googling /([^,]+) but the result array has spaces in class names.

How can I improve the above regex to handle that?

like image 802
VJAI Avatar asked Apr 07 '18 09:04

VJAI


1 Answers

const arr = ' lmn-button ,lmn-button-primary'.trim().split(/\s*,\s*/);
console.log(arr);
like image 97
Alexandre Annic Avatar answered Oct 07 '22 00:10

Alexandre Annic