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.

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!
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With