Home > Web Front-end > JS Tutorial > body text

How to Achieve Look Behind Assertion in JavaScript?

Mary-Kate Olsen
Release: 2024-11-08 20:23:02
Original
568 people have browsed it

How to Achieve Look Behind Assertion in JavaScript?

JavaScript Regex: Alternative to Look Behind Assertion

In JavaScript, the look behind assertion (?) is not supported. This assertion is useful for matching a pattern that is preceded by a specific condition. However, there are alternative ways to achieve the same result in JavaScript.

One alternative is to use the ^ and (?!) pattern. The ^ symbol matches the beginning of a string, while the (?!) checks whether the following expression will not match the current position. For example, the following regex matches any string that ends with .js, except for filename.js:

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

This regex explicitly checks each character of the string to ensure that it does not satisfy the look behind condition.

Another simpler alternative introduced in ECMAScript 2018 is to use the following regex:

^(?!.*filename\.js$).*\.js$
Copy after login

This regex uses the . expression to match any string, and the (?!) assertion to check that the following expression (.filename.js$) will not match the current position. This alternative is more efficient than the first one, as it does not require checking the condition at every character.

The above is the detailed content of How to Achieve Look Behind Assertion 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!