Videos
Continue calling re.exec(s) in a loop to obtain all the matches:
var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';
var m;
do {
m = re.exec(s);
if (m) {
console.log(m[1], m[2]);
}
} while (m);
Try it with this JSFiddle: https://jsfiddle.net/7yS2V/
str.match(pattern), if pattern has the global flag g, will return all the matches as an array.
For example:
const str = 'All of us except @Emran, @Raju and @Noman were there';
console.log(
str.match(/@\w*/g)
);
// Will log ["@Emran", "@Raju", "@Noman"]
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)
}