"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to achieve Negative Lookbehind functionality in JavaScript?

How to achieve Negative Lookbehind functionality in JavaScript?

Published on 2024-11-09
Browse:735

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:

(?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3