Posts

Showing posts with the label regexp

The flag /g of JavaScript’s regular expressions

This blog post describes when and how to use regular expressions whose flag /g is set and what can go wrong. (If you want to read a more general introduction to regular expressions, consult [1] .) The flag /g of regular expressions Sometimes, a regular expression should match the same string multiple times. Then the regular expression object needs to be created with the flag /g set (be it via a regular expression literal, be it via the constructor RegExp ). That leads to the property global of the regular expression object being true and to several operations behaving differently. > var regex = /x/g; > regex.global true The property lastIndex is used to keep track where in the string matching should continue, as we shall see in a moment. RegExp.prototype.test(): determining whether there is a match Regular expressions have the method RegExp.prototype.test(str) Without the flag /g , the method test() of regular expressions simply checks whether there is a mat...