JavaScript Equivalent of Negative Lookbehind
Negative lookbehinds, which match strings that do not begin with a specific character set, are not directly supported by JavaScript regular expressions. However, there are alternative approaches to achieve similar results.
Positive Lookahead and String Reversal
Since JavaScript supports positive lookahead (?=), one method involves:
Example:
const reverse = s => s.split('').reverse().join(''); const regexp = /m(?!([abcdefg]))/; test(['jim', 'm', 'jam'], regexp); function test(strings, regexp) { strings.map(reverse).forEach((s, i) => { match = regexp.test(s); console.log(strings[i], match, 'Token: ', match ? reverse(regexp.exec(s)[0]) : 'Ø'); }); }
Results:
jim true Token: m m true Token: m jam false Token: Ø
Lookbehind Assertions Support (Since 2018)
In 2018, lookbehind assertions, including negative lookbehinds, became part of the ECMAScript language specification. They can be used as follows:
Negative Lookbehind:
(?<!...)
Positive Lookbehind:
(?<=...)
Example:
To match "max-height" but not "line-height":
regexp = /thgieh(?!(-enil))/; test(['max-height', 'line-height'], regexp);
Results:
max-height true Token: height line-height false Token: Ø
The above is the detailed content of How Can I Simulate Negative Lookbehind in JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!