Negative Lookbehind Equivalents in JavaScript
While negative lookbehinds are absent in JavaScript's regular expressions, alternative techniques can achieve similar results.
Lookbehind Assertions (ES2018 and Later)
Since 2018, JavaScript supports lookbehind assertions, including negative lookbehinds. Their syntax is as follows:
Pre-2018 Approach: Reverse Engineering
Before lookbehind assertions were introduced, a multi-step approach was employed:
This approach involved reversing the input and regex patterns, resulting in more complex code.
For example, to match strings excluding certain starting characters:
const reverse = s => s.split('').reverse().join(''); test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/);<p>This approach produced the following results:</p> <pre class="brush:php;toolbar:false">jim true token: m m true token: m jam false token: Ø
By reversing the input and regex, it effectively achieves the desired behavior of matching strings that do not start with specific characters.
The above is the detailed content of How Can I Achieve Negative Lookbehind Functionality in JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!