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

126
Visualizações
javascript regex matchAll

Why does it return true for

  const regex = /\+\+\+\+/gm;

  let test = `+++`

  if (test.matchAll(regex)) {
    alert(true)
  }
  else {
    alert(false)
  }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As per docs:

The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups. - MDN

So if there is a match or not, It will return an iterator object.

In your case, there will not be a match and will return an iterator and it is considered as a truthy value.

You can get all result and collect into an array and then check the length of that array to check for the match as:

const matches = [...test.matchAll(regex)];

If there is no match then matches will be empty array

const regex = /\+\+\+\+/gm;

let test = `+++`;

const matches = [...test.matchAll(regex)];
console.log(matches);
if (matches.length) {
  console.log(true);
} else {
  console.log(false);
}

If there is a match then matches will be an array of matches

const regex = /\+\+\+\+/gm;

let test = `++++`;

const matches = [...test.matchAll(regex)];
console.log(matches);
if (matches.length) {
  console.log(true);
} else {
  console.log(false);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

matchAll returns an iterator, which, when coerced to a boolean, is true.

Perhaps you meant match?

const regex = /\+\+\+\+/gm;

let test = `+++`

if (test.match(regex)) {
  console.log(true)
} else {
  console.log(false)
}

Although for this purpose, RegExp.test() is better:

const regex = /\+\+\+\+/gm;

let test = `+++`

if (regex.test(test)) {
  console.log(true)
} else {
  console.log(false)
}

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