javascript regex matchAll - Stack Overflow

admin2025-04-19  1

Why does it return true for

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

  let test = `+++`

  if (test.matchAll(regex)) {
    alert(true)
  }
  else {
    alert(false)
  }

Why does it return true for

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

  let test = `+++`

  if (test.matchAll(regex)) {
    alert(true)
  }
  else {
    alert(false)
  }
Share Improve this question asked Sep 12, 2021 at 22:24 user310291user310291 38.3k89 gold badges295 silver badges519 bronze badges 1
  • Use the browser console (dev tools) (hit F12). Have you tried putting `+++`.matchAll(/\+\+\+\+/gm) into the console to see what it evaluates as? – Sebastian Simon Commented Sep 13, 2021 at 1:08
Add a ment  | 

2 Answers 2

Reset to default 6

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);
}

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)
}

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745041583a281575.html

最新回复(0)