This is an ideal case for regular expressions!
In this case, you want to do this:
$('#side-categories a').each(function () {
var href = $(this).attr("href");
if(href.match(/\sdog\s/)){
$(this).css("color", "red");
$(this).parents("ul").show().prev('.do').text('-');
}
});
Regular expressions are a good thing to learn. In this case, it's pretty basic. /\sdog\s/
is saying "a regular expression containing some whitespace, the lowercase string dog and some more whitespace." That includes your first line, while eliminating your second (due to the whitespace) and the third (do to the exact string dog
followed by whitespace).
If you're using a variable (such as table
?) to hold the string you're looking for, you need to construct the regular expression. The important lines then become:
var regex = new RegExp("\s" + table + "\s");
if(href.match(regex)){
Based on your comments, it looks like you want to see if the string starts with dog
. If that's the case, you can use regex - you just want new RegExp("^" + table)
. But in that case, you actually could do better with a regular string function, such as if (href.indexOf(table) == 0)
.
In the case of looking for table=dog*
, that's a fairly easy RegExp as well: new RegExp("table=" + table)
. This looks for table=dog
to be anywhere in the string. Without regexp, you'd do similar to above, if (href.indexOf("table=" + table) != -1)
.