Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex101 vs JavaScript String.match disagreement

This regex /{(\w+)}/g is supposed to match every word character between the curly braces {}. Instead, I'm getting different results in the Regex101 JavaScript engine and Chrome console.

regex 101 vs js engine

Regex101 works as expected, and the .match function works without the g flag, but it fails to retrieve the contents between curly braces once I apply it (it should fetch ["asd","asd2"], and instead it fetches ["{asd}","{asd2}"])

Why does this happen? Thanks!

like image 883
undefined Avatar asked Feb 02 '26 16:02

undefined


1 Answers

The String.prototype.match function returns an array of all matches when the 'g' flag is added to the pattern.

You want to use RegExp.prototype.exec function to get the capture groups:

The exec() saves the last index of the match it found in the RegExp object and continues from there when you run it the next time. So, you need to loop over your string until the function returns null to get all the matches.

Demo on JSFiddle

var str = "this {is} a {word} {test}";
var re = /{(\w+)}/g;
do{
var res = re.exec(str);
console.log(res);
} while( res );
like image 95
Eyal Avatar answered Feb 04 '26 06:02

Eyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!