Home > Web Front-end > JS Tutorial > How Can I Achieve Negative Lookbehind Functionality in JavaScript Regular Expressions?

How Can I Achieve Negative Lookbehind Functionality in JavaScript Regular Expressions?

Patricia Arquette
Release: 2024-12-13 15:33:10
Original
129 people have browsed it

How Can I Achieve Negative Lookbehind Functionality in JavaScript Regular Expressions?

Negative Lookbehind Equivalents in JavaScript

While negative lookbehinds are absent in JavaScript's regular expressions, alternative techniques can achieve similar results.

Lookbehind Assertions (ES2018 and Later)

Since 2018, JavaScript supports lookbehind assertions, including negative lookbehinds. Their syntax is as follows:

  • Positive lookbehind: (?<=...)
  • Negative lookbehind: (?

Pre-2018 Approach: Reverse Engineering

Before lookbehind assertions were introduced, a multi-step approach was employed:

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

This approach involved reversing the input and regex patterns, resulting in more complex code.

For example, to match strings excluding certain starting characters:

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

test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/);<p>This approach produced the following results:</p>
<pre class="brush:php;toolbar:false">jim true token: m
m true token: m
jam false token: Ø
Copy after login

By reversing the input and regex, it effectively achieves the desired behavior of matching strings that do not start with specific characters.

The above is the detailed content of How Can I Achieve Negative Lookbehind Functionality in JavaScript Regular Expressions?. 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