Why does it return true for
const regex = /\+\+\+\+/gm;
let test = `+++`
if (test.matchAll(regex)) {
alert(true)
}
else {
alert(false)
}
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)
}