Archive for April 11, 2007

JavaScript match() function g flag

Posted in JavaScript, Software, Web, programming on April 11, 2007 by Joey

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