开发者

Match multiple element's classes using RegExp

开发者 https://www.devze.com 2023-03-09 03:08 出处:网络
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 tr

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消