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
Barbara StreisandOriginal
2024-12-14 15:48:11696browse

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

Results:

jim true Token: m
m true Token: m
jam false Token: Ø

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:

(?<!...)

Positive Lookbehind:

(?<=...)

Example:

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

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

Results:

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

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!

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