Javascript switch statement if string contains substring
I am trying to figure out how to make a switch statement where I need to find the class name for an object and then do something depending on the class name (in a switch statement).
In this example, I need a switch statement to do whatever I want when the class contains a specific word, such as "person".
Html
<div class="person temp something"></div>
Javascript
$(document).on('mousedown', function(e) {
var clicked = $(e.target).attr('class');
console.log(clicked);
switch (clicked) {
case "person":
//do something
break;
default:
//do something
}
});
The switch operator's name, such as "person", is not guaranteed to appear in the first place.
I know I can search through an array for a specific word, but I don't know how to add that to this.
As I said in my comment, the instruction switch
does not seem like a suitable approach in this situation.
Since you are using jQuery, just use : .hasClass
if ($(e.target).hasClass('person')) {
// do something
}
If you want to do something a little more complex for multiple classes, you can create a mapping class -> function
and just loop over the list of classes:
var classActions = {
person: function(element) { /* do something */ },
temp: function(element) { /* do something */},
// ...
};
var classes = e.target.className.split(/\s+/);
$.each(classes, function(index, cls) {
classActions[cls](e.target);
});
You will need a combination of .split () and .indexOf () . Your code will be something like this:
var clicked = $(e.target).attr('class');
var classes = clicked.split(' ');
if(classess.indexOf('person') > 0) {
//do work
} else if (classes.indexOf('foo') > 0) {
//do work
} else if (classes.indexOf('bar') > 0) {
//do work
}
MDN documentation in .split ()
MDN documentation at .indexOf ()
Note that there are many methods that allow you to do this. For example, you can use string.search(substring)
to check if a string contains your substring. If there is a substring, it returns the found index (some number from 0 to n ), otherwise, if it is not found, it returns -1. Therefore, if search
greater than or equal to 0, there is a substring.
if(clicked.search("person") >= 0)
// "person" is in clicked