JavaScript match() function g flag

The match() function is used in JavaScript for regular expression matches. It takes a regular expression as an argument and returns an array containing the matching value(s). If the g flag is set it returns all matches. Without the ‘g’ flag, it returns only the first match. This is still an array but with only one value.

//Returns an array with one element (no ‘g’ flag)
var StringTest = “JavaScript is not Java”;
var ArrayMatch = StringTest.match(/j/i);
alert(ArrayMatch.length);

//Returns an array with two elements (‘g’ flag)
var StringTest = “JavaScript is not Java”;
var ArrayMatch = StringTest.match(/j/gi);
alert(ArrayMatch.length);

The i flag specifies case-insensitivity. I explained this in my post JavaScript Regular Expression Case Sensitivity

One Response to “JavaScript match() function g flag”

  1. Thanks you very much. It is working, true ! Thanks you again. Very nice.

Leave a Reply