Home  >  Article  >  Web Front-end  >  How to achieve Negative Lookbehind functionality in JavaScript?

How to achieve Negative Lookbehind functionality in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 10:58:02410browse

How to achieve Negative Lookbehind functionality in JavaScript?

Alternative Regex for Negative Lookbehind in JavaScript

In JavaScript, negative lookbehind assertions are not directly supported. However, there are ways to achieve similar functionality.

Consider the following regex:

(?<filename)\.js$

This regex matches strings ending with .js except for filename.js. In regex implementations that support lookbehind, this expression would work as intended.

Alternative Using Negative Lookahead

Since JavaScript does not have lookbehind, we can use negative lookahead instead:

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

This expression explicitly checks each character of the string to ensure that the negative lookbehind assertion (?!filename.js$) plus the remaining regex won't match. If it doesn't match, the character is allowed to match.

Simplified Version

For JavaScript versions prior to ECMAScript 2018, the following simplified version can be used:

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

This expression asserts that the string doesn't contain filename.js anywhere and ends with .js.

The above is the detailed content of How to achieve Negative 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