Match multiple element's classes using RegExp
I assign classes to my target elements, in my jquery plugin, like plugin-prop-value
. So elements could have several of the type. Currently i just attr('class').split(' ')
then for
etc. Now I'm trying to access them using regexp directly.
I'm using this pattern /\bplugin-(prop1|prop2|prop3)-(\S+)/g
.
match()
gets me array of matching开发者_运维问答 classes so i have to loop them again. ( loop->regexp, or loop->split )
exec()
gets me only an array of first match [ wholeclass, prop, value ]
, seems g
flag doesn't play here but i was hoping for something more like
[ [ wholeclass, prop, value ], [ ... ], [ ... ] ]
What is the best approach?
To use a regex on a string to match multiple times, you just have to run exec
again:
str = "prop-a prop-b prop-c";
re = /\bprop-([abc])/g;
while ((matches = re.exec(str))) {
console.log(matches[1]);
}
// output is:
// a
// b
// c
var pluginNameValuePairs= $.map(element.className.split(/\s+/), function(cls) {
var parts= cls.split('-');
if (parts.length<3 || parts[0]!=='plugin') return null;
return [parts[1], parts.slice(2).join('-')];
});
If you need to put arbitrary characters in a value, such as whitespace or -
, you might want to URL-encode them too.
jQuery has a hasClass() method which, in so far as I'm aware, caches the class names -- thus avoiding that they need to be parsed again and again.
精彩评论