If I need to see if a certain value is in a string, is it better for performance to use the .test() method or the .search() method?
Example with .search():
var myRegExp = '/Orange/',
myString = 'This is a string with the word "Orange."';
if(myString.search(myRegExp) != -1) {
// Do code here
}
Example with .test():
var myRegExp = '/Orange/',
myString = 'This is a string with the world "Orange."';
if(myRegExp.test(myString)) {
// Do code here
}
Ultimately, what I’m doing is searching for a specific class name in string. The element would contain multiple classes, so I’d need to find if one of the classes is in it.
Example Markup:
<ul>
<li class="expandable expanded">
<ul>
<li>Text</li>
</ul>
<li>
<li class="expandable collapsed">
<ul>
<li>Text</li>
</ul>
</li>
</ul>
So, I’m adding a click event to the list items, if they have the class name “expanded” they need to behave one way, if they have the class name “collapsed” they need to behave another.
So, essentially, something like this.
element.addEventListener('click',function(e) {
if( /* e.target has class name of expanded */ ) {
// Do certain code
} else {
// Do other code
}
}
I am using jQuery, and I am open to suggestions, but I feel this situation would be better served with native javascript. So, which method would give the best performance? Or is there another method that would be even better?
Well, if you are using jQuery, you can do this simply with
If you don’t want to create a jQuery object for whatever reason (e.g. performance) you could use this function, adapted from the source of
$().hasClass():You can then call this like so:
Personally, I would go for the jQuery approach if you already have it loaded.