Negative lookbehind equivalent in JavaScript

Since 2018, Lookbehind Assertions are part of the ECMAScript language specification.

// positive lookbehind
// negative lookbehind

Answer pre-2018

As Javascript supports negative lookahead, one way to do it is:

  1. reverse the input string

  2. match with a reversed regex

  3. reverse and reformat the matches

const reverse = s => s.split('').reverse().join('');

const test = (stringToTests, reversedRegexp) => stringToTests
  .forEach((s,i) => {
    const match = reversedRegexp.test(s);
    console.log(stringToTests[i], match, 'token:', match ? reverse(reversedRegexp.exec(s)[0]) : 'Ø');

Example 1:

Following @andrew-ensley’s question:

test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/)


jim true token: m
m true token: m
jam false token: Ø

Example 2:

Following @neaumusic comment (match max-height but not line-height, the token being height):

test(['max-height', 'line-height'], /thgieh(?!(-enil))/)


max-height true token: height
line-height false token: Ø

Leave a Comment