JavaScript global Property RegExp.global Property (Regular Expressions)

This tutorial explains the global property, part of JavaScript's RegExp object. The global property (or "modifier") determines if a regular expression pattern should be matched more than once. The String object's match() method and RegExp object's exec() method both try to capture substrings matching a regular expression pattern in strings on which they are applied. If the regular expression is set to global, all matches found will be returned (instead of limiting itself to the first match encountered.)

With methods that only check for the presence of a pattern (as opposed to the number of occurrences) the global property will not make a difference.

Using the global Property

To demonstrate the global property, the script below declares a regular expression, without global modifier.

var carter = "On April 4th, 1856, 53 soldiers were killed.";
var arlene = carter.match(/\d/); // global not specified

// Check number of matches
alert( arlene.length );

The regular expression declared above tried to match any digit in our string. Without specifying the global modifier, the script returned: JavaScript global property turned off

We will now re-use our script, this time including the global modifier in our regular expression, by appending a letter "g" after the regular expression literal:

var carter = "On April 4th, 1856, 53 soldiers were killed.";
var arlene = carter.match(/\d/g); // Notice the 'g'

// Check number of matches
alert( arlene.length );

By setting the global property for our regular expression pattern, our script now matched all instances of a digit in our string: JavaScript global property

Declaring the global property

There are several ways to "turn on" the global property for a in JavaScript. First, using the regular expression constructor, or using literal notation:

// Global property with literal notation:
var remo1 = /javascript/g;

// Global property using the constructor:
var remo2 = new RegExp("javascript","g");

The two regular expression above are identical. The global property 'g' modifier can also be used in conjunction with other modifiers, like the ignoreCase property: (which renders regular expressions case-insensitive)

// Global and case-insensitive regular expression
var remo3 = /javascript/gi;

// Same regular expression, declared with the constructor
var remo4 = new RegExp("javascript","gi");

Test the global Property

Interactively test the global property by editing the JavaScript code below and clicking the Test global Property button.

Browser support for JavaScript global property
Internet Explorer supports the JavaScript global propertyFirefox supports the JavaScript global propertySafari supports the JavaScript global propertyOpera supports the JavaScript global property