Achieving Negative Lookbehind Functionality in JavaScript
Negative lookbehind assertions allow for matching a string that does not begin with a specific set of characters. Despite the lack of explicit support for negative lookbehinds in JavaScript, there are viable alternatives.
From 2018 onwards, Lookbehind Assertions have been incorporated into the ECMAScript specification:
// Positive lookbehind: (?<=...) // Negative lookbehind: (?<!...)
Pre-2018 Approach
Alternatively, if negative lookbehinds are unavailable, consider the following approach:
For example:
const reverse = (string) => { return string.split('').reverse().join(''); }; const test = (inputStrings, reversedRegex) => { inputStrings.map(reverse).forEach((reversedString, idx) => { const match = reversedRegex.test(reversedString); console.log( inputStrings[idx], match, 'token:', match ? reverse(reversedRegex.exec(reversedString)[0]) : 'Ø' ); }); };
Example 1: To match "m" in "jim" or "m", but not in "jam":
test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/);
Output:
jim true token: m m true token: m jam false token: Ø
Example 2: To match "max-height" but not "line-height":
test(['max-height', 'line-height'], /thgieh(?!(-enil))/);
Output:
max-height true token: height line-height false token: Ø
The above is the detailed content of How Can I Simulate Negative Lookbehind Assertions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!