Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading