How to use lookahead and lookbehind RegExp in JavaScript

Sometimes you want to ensure that a RegExp pattern starts immediately after a specific string but you don't want to include those characters in the match. In these cases, a lookbehind expression comes in handy.

Lookbehind expressions were initially not available in browsers, but as of the time writing, only IE and Safari lacks the feature. So most modern websites finally use it.

There are four variations of the lookahead/lookbehind expressions as follows:

Expression Name What does it do?
(?=foo) Lookahead Asserts that foo follows immediately after the current position
(?<=foo) Lookbehind Asserts that the current position is immediately preceded by foo
(?!foo) Negative lookahead Asserts that what follows immediately after the current position is not foo
(?<!foo) Negative lookbehind Asserts that what immediately precedes the current position is not foo

Some example using lookbehind and negative lookahead:

const pattern = /(?<=red,)green(?!,blue)/;

// Does not replace green as the last color is blue
'red,green,blue'.replace(pattern, 'orange');
// Returns: "red,green,blue"

// Replaces green as the last color is not blue
'red,green,black'.replace(pattern, 'orange');
// Returns: "red,orange,black"

All done!