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

How to achieve Negative Lookbehind functionality in JavaScript?

Susan Sarandon
Release: 2024-11-09 10:58:02
Original
473 people have browsed it

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$
Copy after login

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$
Copy after login

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$
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template