-2

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 perfectly:

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 a 'solo'.

MORÈ
  • 2,480
  • 3
  • 16
  • 23
  • 2
    You have unclosed `"` in your sample code – qrsngky Nov 10 '22 at 04:08
  • is this you answer? https://stackoverflow.com/questions/31340868/includes-not-working-in-all-browsers – nariman zaeim Nov 10 '22 at 04:18
  • Both `"my-Solo".includes("Solo")` and `"my-Solo".includes("my-Solo")` are `true`. There are a few tools to inspect strings. E.g., when doing `"my-Solo".length`, I expect `7`. When doing `Array.from("my-Solo")`, I expect `[ "m", "y", "-", "S", "o", "l", "o" ]`. When doing `Array.from("my-Solo", (string) => string.codePointAt())`, I expect `[ 109, 121, 45, 83, 111, 108, 111 ]`. When doing `Array.from("my-Solo", (string) => string.codePointAt().toString(16).toUpperCase().padStart(2, "0")).join(" ")`, I expect `"6D 79 2D 53 6F 6C 6F"`. [Edit] your post and provide a [mre] we can work with. – Sebastian Simon Nov 10 '22 at 04:23
  • 1
    Since the answer below has been accepted, this means that the string in the actual code does not match in case (i.e. lower or upper case). But since it does in the code shown, I’m voting to close as off-topic, since the issue is not reproducible, thus not helpful for future readers. – Sebastian Simon Nov 11 '22 at 07:07

1 Answers1

1

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.