Javascript regular expression examples

Last updated:

String matches regexp

Check whether it 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
    console.log(result[1]); //this is where the actual result is kept
// 12345

Remove pattern from string

// Removing the first series of numbers from a string
// In other words, replace it with an empty string
var str = "foo bar94857 baz 894 quux";
// "foo bar baz 894 quux"

Remove all occurrences of pattern from string

// Remove all numbers from a string
// In other words, replace it with an empty string
var str = "foo bar94857 baz 894 quux";
// "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";
// "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";
// "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

// this one doesn't 

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?

Dialogue & Discussion