Home > Web Front-end > JS Tutorial > body text

Can Negative Lookahead Mimic Regex Lookbehind in JavaScript?

Susan Sarandon
Release: 2024-11-12 21:30:02
Original
520 people have browsed it

Can Negative Lookahead Mimic Regex Lookbehind in JavaScript?

Negative Lookahead in JavaScript: An Alternative to Regex Lookbehind

Question:

In JavaScript, which lacks Regex lookbehind, is there a way to match a specific pattern excluding a certain condition?

Answer:

Prior to ECMAScript 2018, JavaScript did not natively support negative lookbehind assertions. Here's an alternative approach:

^(?:(?!filename\.js$).)*\.js$
Copy after login

Explanation:

This regex simulates lookbehind by explicitly checking each character of the string. If the lookbehind expression ("filename.js$"), followed by the rest of the regex (".js$"), does not match at the current character, the character is permitted.

^                 # Start of string
(?:               # Try to match the following:
 (?!              # First assert that we can't match the following:
  filename\.js    # filename.js 
  $               # and end-of-string
 )                # End of negative lookahead
 .                # Match any character
)*                # Repeat as needed
\.js              # Match .js
$                 # End of string
Copy after login

However, a simpler alternative has emerged since then:

^(?!.*filename\.js$).*\.js$
Copy after login

This latter approach is more efficient as it does not check the lookahead at every character.

^                 # Start of string
(?!               # Assert that we can't match the following:
 .*               # any string, 
  filename\.js    # followed by filename.js
  $               # and end-of-string
)                 # End of negative lookahead
.*                # Match any string
\.js              # Match .js
$                 # End of string
Copy after login

The above is the detailed content of Can Negative Lookahead Mimic Regex Lookbehind 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