Search code examples
javascriptregexnegative-lookbehind

Negative lookbehind equivalent in JavaScript


Is there a way to achieve the equivalent of a negative lookbehind in JavaScript regular expressions? I need to match a string that does not start with a specific set of characters.

It seems I am unable to find a regex that does this without failing if the matched part is found at the beginning of the string. Negative lookbehinds seem to be the only answer, but JavaScript doesn't has one.

This is the regex that I would like to work, but it doesn't:

(?<!([abcdefg]))m

So it would match the 'm' in 'jim' or 'm', but not 'jam'


Solution

  • Lookbehind Assertions got accepted into the ECMAScript specification in 2018.

    Positive lookbehind usage:

    console.log(
      "$9.99  €8.47".match(/(?<=\$)\d+\.\d*/) // Matches "9.99"
    );

    Negative lookbehind usage:

    console.log(
      "$9.99  €8.47".match(/(?<!\$)\d+\.\d*/) // Matches "8.47"
    );

    Platform support