Home  >  Article  >  Web Front-end  >  Can Negative Lookahead Mimic Regex Lookbehind in JavaScript?

Can Negative Lookahead Mimic Regex Lookbehind in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 21:30:02522browse

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$

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

However, a simpler alternative has emerged since then:

^(?!.*filename\.js$).*\.js$

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

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!

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