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!