我需要在CSS中将CSS类名字符串拆分为CSS类名称数组.以下所有字符串应生成相同的数组.
'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
Run Code Online (Sandbox Code Playgroud)
目前我正在使用代码来做到这一点,
cssClassesString.split(',').map(cssClass => cssClass.trim());
Run Code Online (Sandbox Code Playgroud)
但我相信正则表达式会是一个更好的解决方案吗?
我通过谷歌搜索获得了这个正则表达式,/([^,]+)但结果数组在类名中有空格.
如何改进上述正则表达式来处理?
const arr = ' lmn-button ,lmn-button-primary'.trim().split(/\s*,\s*/);
console.log(arr);Run Code Online (Sandbox Code Playgroud)