Regular Expressions in JavaScript

March 18, 2010

Here's some code examples for working with regular expressions in JavaScript (with a bit of jQuery thrown in for good measure)

Search and Replace

Here's an example of looking for matches to a regex and replacing. The $1 in the replace refers to the string that matched.

  var lRegExText = '(' + $('#regex').val() + ')';
  var lRegExOptions = $('#options').val();
  var lText = $('#sourcetext').val();
  var lRegEx = new RegExp(lRegExText, lRegExOptions);
  var lResults = lText.replace(lRegEx, "<font color='red'><b>$1</b></font>");

RegEx Literals

You can use regular expression literals in JavaScript code. The following two lines are identical.

var lRegEx = new RegExp('[A-Z]*', 'gm');
var lRegEx = /[A-Z]*/gm


How to find out if a string matches the specified regex.

var lRegEx = new RegExp("e");
var lOutput = lRegEx.test("The best things in life are free");

lOutput contains true, as there is an e in the string.

Finding Matched Text

Here's an example to find the text that matched.

var lResult = lStringToSearch.match(/\d+/);
if (lResult) {
  lResult = lResult[0];
} else {
  lResult = '';

lResult contains the part of the string that matched.

Find Match Location

This example shows how to find the location in the string that matched.

var lMatchStart = -1;
var lMatchLength = -1;
var lMatch = /\d+/.exec(lStringToSearch);
if (lMatch){
  lMatchStart = lMatch.index;
  lMatchLength = lMatch[0].length;

Returns the position in the string that matched. Don't use lastIndex property of the array returned by exec() - it has various bugs in different browsers.

Capture Groups

Capture groups, the brackets in the regex, can be obtained using the array returned from exec(). Here we're getting the first group.

var lResult = '';
var lMatch = /http:\/\/([a-zA-Z0-9.-]+)/.exec(lStringToSearch);
if (lMatch){
  lResult = lMatch[1];
} else {
  lResult = '';

This returns the hostname or ip part of the url if there is a match.


Options for JavaScript are:

  • i - case insensitive matching
  • g - find all matches rather than stopping after the first match
  • m - multiline matching