Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
String.prototype.includes() returns true when it shouldn't

Recently while solving some coding problems I ran into a weird situation where i had to check if: String starts with another string

I solved it quite simply with

if(string.includes(substring))
{
 //code
}

And it worked..... BUT it returned TRUE when:

const string = "is it you or is it me or what?";
const substring = "is it me or";

What is the reason behind this returning true? I even tried on different compiler websites and they all returned true. I really am puzzled as my understanding of .includes() is that it should check if a string contains the sub-string.

EDIT: I'm actually blind and i didn't notice that it contains the same string in middle of the sentence. Sorry, didn't have much sleep.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you only need to return true if string starts with substring, use .startsWith() instead. For example:

> 'abc'.startsWith('a')
true

> 'abc'.startsWith('b')
false

Both .contains() (deprecated now, but might be supplied by polyfill) and .includes() (supported universally), however, will return true in both cases, as it checks whether or not a substring is contained within a given string, not necessarily at its beginning:

> 'abc'.includes('a')
true
> 'abc'.includes('b')
true

To answer your specific question, is it me or is part of that bigger string. You can use .indexOf() as a little helper here to provide you the exact position of that string:

const string = "is it you or is it me or what?";
const substring = "is it me or";
string.indexOf(substring); // 13
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda