Home  >  Article  >  Web Front-end  >  How to Achieve Regex Lookbehind Functionality in JavaScript?

How to Achieve Regex Lookbehind Functionality in JavaScript?

DDD
DDDOriginal
2024-11-13 12:41:02642browse

How to Achieve Regex Lookbehind Functionality in JavaScript?

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."

The above is the detailed content of How to Achieve Regex Lookbehind Functionality 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