Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!