Question

I am trying to achieve the following: I have an element(s) and all of them can have classes assigned to them (some has "a1", some "a2", "a3"... or they can be without class). I need to check (in condition) if I am dealing with any of "a*"-class element, or with non-"a*"-class element. Obvious way would be:

if (element.prop('class')=='a1' || element.prop('class')=='a2' ||...){ // some action}

but since number of different "a" classes is dynamic and can go to high numbers, I would like to test rather for something like this

if (element.prop('class')=='a\d'){ // some action}

or replacing /d with [0-9]. A have done quite some research on this regular expressions, but haven't find anything suitable neither working. Is there any preferably Regex-way(or similar) or any alternative to my problem?

Thank you

Was it helpful?

Solution

JavaScript has regular expression literals, and you'd want to use the test method:

if (/a\d/.test(element.attr('class'))) { 
    // some action
}

Side note: class is an HTML attribute, not a node property (use attr not prop)

OTHER TIPS

I'd suggest this regex:

/(^|\s)a\d/

Because it looks for the a at the beginning of the string or after a space, so it will work in cases where the element had more than one class specified, like class="b2 a1", but won't accept class names that have other letters before the a, like class="ha1".

So:

if (/(^|\s)a\d/.test(element.prop('class')) {

Note that you don't test against a regex using == like you had in your code. You use regex methods like .test().

And the regex itself is created either as a regex literal, where you put the expression in between two forward slashes like this:

/(^|\s)a\d/

Or as a string that you pass to new RegExp() like:

new RegExp('(^|\\s)a\\d')

...but doing it with a string is more hassle because you have to escape any backslashes in the string (notice in my example they're doubled?), so I'd only do that when building a regex out of variables such as when it needs to include data entered by the user.

if ( element.prop('class')[0]=='a' && !isNaN(element.prop('class').substring(1)) )

May be, I guess, faster than any regular expression

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top