Home >Web Front-end >JS Tutorial >How Can I Simulate Negative Lookbehind Assertions in JavaScript?

How Can I Simulate Negative Lookbehind Assertions in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 16:27:13703browse

How Can I Simulate Negative Lookbehind Assertions in JavaScript?

Achieving Negative Lookbehind Functionality in JavaScript

Negative lookbehind assertions allow for matching a string that does not begin with a specific set of characters. Despite the lack of explicit support for negative lookbehinds in JavaScript, there are viable alternatives.

From 2018 onwards, Lookbehind Assertions have been incorporated into the ECMAScript specification:

// Positive lookbehind:
(?<=...)

// Negative lookbehind:
(?<!...)

Pre-2018 Approach

Alternatively, if negative lookbehinds are unavailable, consider the following approach:

  1. Reverse the input string.
  2. Match against a reversed regular expression.
  3. Reverse and reformat the resulting matches.

For example:

const reverse = (string) => {
  return string.split('').reverse().join('');
};

const test = (inputStrings, reversedRegex) => {
  inputStrings.map(reverse).forEach((reversedString, idx) => {
    const match = reversedRegex.test(reversedString);
    console.log(
      inputStrings[idx],
      match,
      'token:',
      match ? reverse(reversedRegex.exec(reversedString)[0]) : 'Ø'
    );
  });
};

Example 1: To match "m" in "jim" or "m", but not in "jam":

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

Output:

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

Example 2: To match "max-height" but not "line-height":

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

Output:

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

The above is the detailed content of How Can I Simulate Negative Lookbehind Assertions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn