You can use the following function using a regular expression to match your string surrounded by a space or the beginning or end of a string. But you should be careful when preparing any special regular expression characters if you plan to use them, since the search argument will be interpreted as a string instead of the RegExp literal:
var hasClass = function(s, klass) { var r = new RegExp("(?:^| )(" + klass + ")(?: |$)") , m = (""+s).match(r); return (m) ? m[1] : null; }; hasClass("abc", "a"); // => "a" hasClass("abc", "b"); // => "b" hasClass("abc", "x"); // => null var klasses = "widget util cookie i18n-username"; hasClass(klasses, "username"); // => null hasClass(klasses, "i18n-username"); // => "i18n-username" hasClass(klasses, "i18n-\\w+"); // => "i18n-username"
As others pointed out, you can also just use βsplitβ and βindexOfβ:
var hasClass = function(s, klass) { return (""+s).split(" ").indexOf(klass) >= 0; };
However, note that the "indexOf" function has been introduced in JavaScript a bit recently, so for older browsers you may have to implement it yourself.
var hasClass = function(s, klass) { var a=(""+s).split(" "), len=a.length, i; for (i=0; i<len; i++) { if (a[i] == klass) return true; } return false; };
[change]
Note that the split / indexOf solution is likely to be faster for most browsers (though not for all). This jsPerf benchmark shows which solution runs faster for different browsers - especially Chrome should have a really good regex engine!
source share