1

Hi there I am currently working in a javascript project, though I cam across a problem, I don't know how to check if something is a part of a string. I know you don't understand what that means but to give you a n example of how you would do it in python.

if "a" in "abc":
    print("a")

How do you do this in js can anyone tell me? Thank you in advance.

Shend Tytynxhiu
  • 127
  • 1
  • 9
  • 1
    `if("abc".indexOf("a") > -1){...}` – Scott Marcus Dec 20 '20 at 14:58
  • you don't know how much time I spend trying to figure this out – Shend Tytynxhiu Dec 20 '20 at 14:59
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – Scott Marcus Dec 20 '20 at 14:59
  • 1
    @ScottMarcus Modern JS has [`.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) now. – Ouroborus Dec 20 '20 at 15:02
  • .includes is a closer equivalent and shorter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes – David Frederick Dec 20 '20 at 15:02
  • @Ouroborus Ok, but it's 2 characters shorter. Not earth shattering. – Scott Marcus Dec 20 '20 at 15:03
  • @ScottMarcus Not sure what that has to do with it. Instead, you're dropping a returned value and a comparison. Not a big deal if you're just using it once but nice to be aware of for larger tasks. – Ouroborus Dec 20 '20 at 15:05
  • Thank you everyone for telling me how to solve my problem – Shend Tytynxhiu Dec 20 '20 at 15:31
  • @Ouroborus Those same operations are being performed internally by `includes()`. It's just abstracted away into the method call so you're not saving anything on performance like you think you are. I replied about the characters because you said it's shorter. – Scott Marcus Dec 20 '20 at 15:39
  • @ScottMarcus Sure, but the difference may be that that the abstraction is in a faster implementation. Performance testing would sus out the difference, if any. Also, I didn't say it was shorter, that was somebody else. – Ouroborus Dec 20 '20 at 15:46
  • @Ouroborus My mistake. Meant it for David F. – Scott Marcus Dec 20 '20 at 15:47
  • @ScottMarcus I did look into it. Turns out, as you say, the performance difference is negligible even for large tasks. The real difference is in their behaviors. `.indexof(...) >= 0` doesn't respond identically compared to `.includes(...)`. – Ouroborus Dec 20 '20 at 15:52

1 Answers1

1
if ("abc".includes("a")) console.log("a")
colado
  • 307
  • 4
  • 13