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
Release: 2024-12-26 16:27:13
Original
710 people have browsed it

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:
(?<!...)
Copy after login

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]) : 'Ø'
    );
  });
};
Copy after login

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

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

Output:

jim true token: m
m true token: m
jam false token: Ø
Copy after login

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

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

Output:

max-height true token: height
line-height false token: Ø
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template