Error:

Simple pattern matching

var r = /^\d+$/;
// true
var allDigits = r.test('01234');

Case-insensitive pattern matching

var r = /foo/i;
// true
var containsFoo = r.test('Foo Bar');

Simple pattern substitution

var s = 'Foo Bar Foo';
// first occurrence
// s1 is 'FFF Bar Foo'
var s1 = s.replace(/foo/i, 'FFF');
// all occurrence
// s1 is 'FFF Bar FFF'
var s2 = s.replace(/foo/gi, 'FFF');

Match if X is followed by Y

var sOk = 'foobar';
var sNotOk = 'fooNOTbar';
var r = /foo(?=bar)/;
// b is true
var b = r.test(sOk);
// b is false
b = r.test(sNotOk);

Match if X is not followed by Y

var sNotOk = 'foobar';
var sOk = 'fooNOTbar';
var r = /foo(?!bar)/;
// b is true
var b = r.test(sOk);
// b is false
b = r.test(sNotOk);

Do not remember (non-capturing) match

// ?: - non-capturing
var r = /foo(?:bar){1,2}/;

Swap words

var name = 'John Smith';
var r = /^(\w+)\s+(\w+)$/;
// formalized is "Smith, John"
var formalized = name.replace(r, "$2, $1");

Access matched string

var namePattern = /^(\w+)\s+(\w+)$/;
var name = "John Smith";
var isOK = namePattern.exec(name);
if (!isOK)
    console.log('Mismatch');
else
    console.log('First name: ' + isOK[1] + ', last name: ' + isOK[2]);

Used matched string in substitution

var name = 'John Smith';
var r = /^(\w+)\s+(\w+)$/;
// formalized is "Smith, John"
var formalized = name.replace(r, "$2, $1");

Replaceing the Nth occurrence of a pattern

var s = "How do you do?";
var counter = 0;
// s is 'How do you dO?'
s = s.replace(/o/g, function (match, i, original) {
    counter++;
    return (counter === 4) ? "O" : match;
});

Finding the Nth occurrence of a match

var s = "six one four seven seven eight";
var r = /(zero|one|two|three|four|five|six|seven|eight|nine)/gi;
var counter = 0;
var result;
while (result = r.exec(s)) {
    counter++;
    if (counter == 4) {
        console.log('Fourth digit is ' + result[1]);
        break;
    }
}

Matching multiple lines

var s = "One\nTwo\nThree\nFour";
var r1 = /One.*Four/;
var r2 = /One[\s\S]*Four/;
// false
var matches = r1.test(s);
// true
matches = r2.test(s);

Greedy and non-greedy matches

var s = 'fooooooooo';
var greedy = /(foo+)/;
var nongreedy = /(foo+?)/;
var result = greedy.exec(s);
// fooooooooo
console.log(result[1]);
var result = nongreedy.exec(s);
// foo
console.log(result[1]);

AND, OR and NOT matches

// foo or bar
var regexp_foo_or_bar = /foo|bar/;
var regexp_foo_and_bar = /(?=.*foo)(?=.*bar)/;
var regexp_foo_and_not_bar = /(?=.*foo)(?!.*bar)/;