[英]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. 我需要在CSS中将CSS类名字符串拆分为CSS类名称数组。 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. 我通过googling
/([^,]+)
获得了这个正则表达式,但结果数组在类名中有空格。
How can I improve the above regex to handle that? 如何改进上述正则表达式来处理?
const arr = ' lmn-button ,lmn-button-primary'.trim().split(/\\s*,\\s*/); console.log(arr);
You may simply extract all substrings that consist of 1+ chars other than whitespace and comma. 您可以简单地提取包含除空白和逗号之外的1个字符的所有子字符串。
var result = s.match(/[^,\s]+/g)
See the regex demo . 请参阅正则表达式演示 。
The [^...]
is a negated character class matching any char but the one(s) specified in the class. [^...]
是一个否定的字符类,匹配任何char,但是类中指定的char。 ,
matches commas and \\s
matches any whitespace chars, so [^,\\s]
matches any char but a comma and whitespace. ,
匹配逗号和\\s
匹配任何空格字符,因此[^,\\s]
匹配任何字符,但逗号和空格。 +
quantifier matches 1+ consecutive occurrences of such chars. +
量词匹配1个连续出现的此类字符。
JS demo: JS演示:
var tests = ['lmn-button,lmn-button-primary', 'lmn-button, lmn-button-primary', 'lmn-button ,lmn-button-primary',' lmn-button ,lmn-button-primary', 'lmn-button ,lmn-button-primary ']; var rx = /[^\\s,]+/g; for (var s of tests) { console.log(s, "=>", s.match(rx)); }
你可以用它吗?
console.log('lmn-button ,lmn-button-primary'.split(/[ ,.]+/));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.