JavaScript Regular Expression - Lookahead and Lookbehind

JavaScript Regular Expression - Lookahead and Lookbehind

Jul 15, 2022·

2 min read

When using regular expression, sometimes we not only care about the pattern we want to match, but also we want to make the surrounding pattern as a factor if the current pattern should be matched. For example, if we want to match the number only preceded by a $ character, but we only want the number, without the $ in outcome. This is what look ahead and look behind used for.

There are totally 4 types:

  • Positive lookahead: check if targeted pattern followed by specified pattern
  • Negative lookahead: check if targeted pattern not followed by specified pattern
  • Positive lookbehind: check if targeted pattern preceded by specified pattern
  • Negative lookbehind: check if targeted pattern not preceded by specified pattern

Now let's see some examples to see how they works.

Positive lookahead

Below example shows only match numbers followed by %.

let str = "1# 2% 3 4%";

str.match(/\d+/g)
// ['1', '2', '3', '4']

str.match(/\d+(?=%)/g)
// ['2', '4']

Negative lookahead

Use the same example string, to match numbers not followed by %.

str.match(/\d+(?!%)/g)
// ['1', '3']

Positive lookbehind

Below example shows only match numbers preceded by %.

let str = "#1 %2 3 %4";

str.match(/\d+/g)
// ['1', '2', '3', '4']

str.match(/(?<=%)\d+/g)
// ['2', '4']

Negative lookbehind

Use the same example string, to match numbers not preceded by %.

str.match(/(?<!%)\d+/g)
// ['1', '3']