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

  • A+

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?

const arr = ' lmn-button ,lmn-button-primary'.trim().split(//s*,/s*/); console.log(arr);


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: