Regex Lookbehind Alternative in JavaScript
Problem:
JavaScript does not offer a native method for regex lookbehinds. Consequently, the following regular expression, which functions effectively in other implementations, fails in JavaScript:
(?<!filename)\.js$
This regex aims to match the ".js" extension at the end of a string, but only if it is not preceded by "filename.js."
Solution:
One approach to simulate a regex lookbehind in JavaScript involves employing helper functions. However, a more straightforward alternative regex achieves the desired result:
^(?:(?!filename.js$).)*.js$
Explanation:
This regex employs a negative lookahead to verify that each character in the string does not match the expression "filename.js" followed by the end of string. Only then can that character match the regex. Below is a breakdown of the regex:
^ # 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
Improved Solution:
A more efficient method to achieve the same result is to use the following regex:
^(?!.*filename.js$).*\.js$
This regex asserts that the entire string must not contain "filename.js" and subsequently matches any string ending in ".js."
위 내용은 JavaScript에서 Regex Lookbehind 기능을 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!