Javascript regular expression examples

Javascript regular expression examples

Last updated:
Table of Contents

String fully matches regex

Include ^ at the beginning and $ at the end of the regex pattern

Check whether str.match(pattern) is not null:

var str = 'foo'
console.log( str.match(/^fo$/) !== null );
// false

String contains regex

Check whether str.match(pattern) is not null:

var str = 'foo'
console.log( str.match(/fo/) !== null );
// true

Extract pattern from string

Say you have a string and you want to test whether it is of the form "foobar<a number>baz"and, in case it matches, you want to know what <a number> is.

var str = "foobar12345baz";
var result = str.match(/foobar(\d+)baz/);

if ( result === null ){
    console.log('no match'); // null means no match
}else{
    console.log(result[1]); //this is where the actual result is kept
}
// 12345

Replace pattern in string, only first match

Only the first match gets replaced.

Example: replace numbers with a letter 'X'

var str = "foo123bar456";
console.log(str.replace(/\d+/,"X"));
// "fooXbar456"

Replace all occurrences of pattern in string

note the /g modifier

Example: Replace all sequences of digits with 'X'

var str = "foo123bar456";
console.log(str.replace(/\d+/g,"X"));
// "fooXbarX"

Remove pattern from string

Example: Remove the first sequence of digits from string

// In other words, replace it with an empty string
var str = "foo bar 123 baz 456 quux";
console.log(str.replace(/\d+/,""));
// "foo bar  baz 456 quux"

Remove all occurrences of pattern from string

note the /g modifier

Example: Remove all sequences of digits from string

// In other words, replace it with an empty string
var str = "foo bar 123 baz 456 quux";
console.log(str.replace(/\d+/g,""));
// "foo bar  baz  quux"

Capture and replace with capture groups

Variables like $1 when placed in the replacement string, reference the capture group (sections of regular expressions within ()) in the regular expression argument:

var str = "foo b123 baz";
console.log(str.replace(/(\w)\d+/,'$1'));
// "foo b baz"

Capture and replace multiple capture groups

If there are multiple capture groups, the first one is referenced by $1, the second one by $2 and so on:

var str = "foo b123  c456 baz";
console.log(str.replace(/(\w)\d+\s+\w(\d+)/,'$1--$2'));
// "foo b--456 baz"

Regular expressions with variables

You need to use the RegExp constructor.

var name = "john";

// you can pass modifiers as a second parameter
var john_re = new RegExp(name,'i');

// these match
console.log("JOHN".match(john_re));
console.log("jOhn".match(john_re));

// this one doesn't 
console.log("mary".match(john_re));

Javascript isn't so ugly once you set a little time aside to learn it properly.

In any case, no matter what server-side platform we develop in, we'll have to know some of it to solve our problems so why not tame the damned beast already?