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

How Can I Simulate Negative Lookbehind in JavaScript Regular Expressions?

Barbara Streisand
Release: 2024-12-14 15:48:11
Original
634 people have browsed it

How Can I Simulate Negative Lookbehind in JavaScript Regular Expressions?

JavaScript Equivalent of Negative Lookbehind

Negative lookbehinds, which match strings that do not begin with a specific character set, are not directly supported by JavaScript regular expressions. However, there are alternative approaches to achieve similar results.

Positive Lookahead and String Reversal

Since JavaScript supports positive lookahead (?=), one method involves:

  1. Reversing the input string.
  2. Using a reversed regex with positive lookahead.
  3. Reversing and reformatting the matches.

Example:

const reverse = s => s.split('').reverse().join('');
const regexp = /m(?!([abcdefg]))/;

test(['jim', 'm', 'jam'], regexp);

function test(strings, regexp) {
  strings.map(reverse).forEach((s, i) => {
    match = regexp.test(s);
    console.log(strings[i], match, 'Token: ', match ? reverse(regexp.exec(s)[0]) : 'Ø');
  });
}
Copy after login

Results:

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

Lookbehind Assertions Support (Since 2018)

In 2018, lookbehind assertions, including negative lookbehinds, became part of the ECMAScript language specification. They can be used as follows:

Negative Lookbehind:

(?<!...)
Copy after login

Positive Lookbehind:

(?<=...)
Copy after login

Example:

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

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

Results:

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 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