[Solved] Find piece of string inside array and do something if I can find it


Your question still isn’t explained very well, but I think I have it.

You’re asking why this returns true:

if($(this).html().indexOf("Title A") != -1) {
    //should get here
}

But this doesn’t:

var titles = ["Title A"];
var realTitle = $(this).html();
if (titles.indexOf(realTitle) > -1) {
    //should get here
}

The difference has to do with the difference between string.indexOf() and array.indexOf().

string.indexOf() searches for the specified text anywhere in the string.

array.indexOf() searches for the specified object (doesn’t have to be a string) anywhere in the array.

Edit From your picture, I can see that your span contains a lot of whitespace. Try changing to this:

var realTitle = $.trim($(this).text());

Edit 2 in response to your comment:

In that case, you’ll need to iterate the array and do indexOf on each item. I think this is what you want:

var realTitle = $.trim($(this).text());

for (var i = 0; i < titles.length; i++) {
    if (realTitle.indexOf(titles[i]) > -1) {
        $(this).parent().parent().parent().parent().css("background", colorBackground);
        $(this).parent().parent().parent().parent().find(".row1").css("background", colorBackground);
        $(this).parent().parent().parent().parent().find(".row2").css("background", colorBackground);
        break;
    }
}

3

solved Find piece of string inside array and do something if I can find it