javascript if statement includes value not working

I have an if statement that should check if a value is included if so it does a task. The issue that I have is that its not working

Does not work

var item ="my-Solo

if (item.includes('Solo')) {
  // handle task here
}

This works

var item ="my-Solo

if (item.includes('my-Solo')) {
  // handle task here
}

I need the first example to work because I don’t know what the full string will be but I know it will contain solo

>Solution :

Your code looks fine and it should work. But, as pointed by @qrsngky, your example code has an unclosed ". Anyways, not sure why exactly your first solution isn’t working, when it is correct.
You could also use indexOf() to validate whether you have that item or not. It’ll be something like this:

var item = "my-Solo";
if (item.indexOf('Solo') > -1) {
    // handle task here
}

Also, whenever looking for substrings, if the search is case insensitive, I’d personally suggest to do a lower case.

var item = "my-Solo"
var subStringToSearchFor = "Solo";
if (item.toLowerCase().includes(subStringToSearchFor).toLowerCase()) {
  // handle task here
}

Can apply the toLowerCase() in the indexOf() solution I gave.

Leave a Reply