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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With