JavaScript Tutorials - Regular Expressions

Regular ExpressionsS2C Home « Regular Expressions

In this lesson we look at regular expression creation using the RegExp object or literal format. We also investigate the effect flags have on our pattern matching.

A RegExp object describes a pattern of characters.

Using regular expression patterns and the properties and methods of the RegExp object allows us to check, format, match, parse, substitute and search and replace characters.

Regular Expression Anatomy

A regular expression consists of the pattern we wish to work with along with optional flags that tell us how and where to search for the pattern.

We can use special characters within the pattern to decide which characters to incorporate. Look at the JavaScript Reference - RegExp constructor for tables listing the special characters available and their meanings.

Regular Expression Creation

Regular expression can be created using the RegExp constructor or created using literal format.

Regular expression created using the RegExp constructor need special characters escaped using the \ (backslash symbol). Regular expressions created using literal format do not require this.

Following are examples of creating regular expressions using the RegExp constructor and literal format.


// Create using constructor
var newRegExp = new RegExp('\\d'); // escape required
// Create using literal format
var newRegExp = /\d/; // escape not required

Regular Expression Flags

Flags can be used individually or in combination and are applied to the characters we are searching with the regular expression pattern.

  • g - global match - finds all matches rather than stopping after a match.
  • i - ignore case - case insensitive match.
  • m - line match - match each line.

Following are examples of some simple regular expressions with flag usage.


// Test a regexp pattern against a string using various flags
var regexpArray = new Array(4);
var aString = new String('The thing, the thang and The theng');
var patt0=/the/;
var patt1=/the/i;
var patt2=/the/g;
var patt3=/the/ig;
regexpArray[0] = 'no flags:   ' + aString.match(patt0) + '\n';
regexpArray[1] = 'i flag:   ' + aString.match(patt1) + '\n';
regexpArray[2] = 'g flag:   ' + aString.match(patt2) + '\n';
regexpArray[3] = 'i and g flags:   ' + aString.match(patt3);
alert(regexpArray);

Press the button below to action the above code:


Lesson 9 Complete

In this lesson we looked at regular expression creation using the RegExp object and literal format. We also investigated the effect flags have on our pattern matching. This is the last lesson in the intermediate section of the site for JavaScript.

Related Tutorials

JavaScript Basic Tutorials - Lesson 8 - Strings

What's Next?

We summarize the lessons available for use in the JavaScript Advanced section of the site.

JavaScript Reference

RegExp constructor

go to home page Homepage go to top of page Top