Skip to content

Instantly share code, notes, and snippets.

@spyesx
Last active June 10, 2020 10:39
Show Gist options
  • Save spyesx/b58d61f280fae9f2f95a to your computer and use it in GitHub Desktop.
Save spyesx/b58d61f280fae9f2f95a to your computer and use it in GitHub Desktop.
jQuery.hasClassRegEx() hasClass by using a Regex
(function($)
{
$.fn.hasClassRegEx = function(regex)
{
var classes = $(this).attr('class');
if(!classes || !regex){ return false; }
classes = classes.split(' ');
var len = classes.length;
for(var i=0; i<len; i++)
{
if(classes[i].match(regex)){ return true; }
}
return false;
};
})(jQuery);
/*
<span id="hasClassRegEx" class="Test Testing someTest aaTestaa"></span>
$("#hasClassRegEx").hasClassRegEx(); // false
$("#hasClassRegEx").hasClassRegEx(''); // false
$("#hasClassRegEx").hasClassRegEx('Test'); // true
$("#hasClassRegEx").hasClassRegEx(/ /); // false
$("#hasClassRegEx").hasClassRegEx(/Test/); // true
$("#hasClassRegEx").hasClassRegEx(/^Test/); // true
$("#hasClassRegEx").hasClassRegEx(/Test$/); // true
$("#hasClassRegEx").hasClassRegEx(/^Test$/); // true
$("#hasClassRegEx").hasClassRegEx(/test/); // false
$("#hasClassRegEx").hasClassRegEx(/test/i); // true
*/
@naturalkei
Copy link

Please correct the incorrect equation.
Line 12: for(var i=0; i>len; i++)
// --> i < len

@spyesx
Copy link
Author

spyesx commented Jun 2, 2018

@Euiyeon I see your comment only now... Sorry for the delay and thank you for the alert. It's updated now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment