Home >Web Front-end >JS Tutorial >How Can I Implement Negative Lookbehind in JavaScript Regex?
How to Implement Negative Lookbehind in JavaScript
JavaScript does not natively support negative lookbehinds, which hinders the creation of regular expressions that match strings that do not start with specific characters.
Solution with Lookbehind Assertions (post-2018)
In 2018, JavaScript introduced lookbehind assertions, allowing for both positive and negative lookbehinds:
For example, the following regex matches the 'm' character in 'jim' or 'm', but not in 'jam':
(?<!([abcdefg]))m
Solution Pre-2018
Before 2018, one workaround involved reversing the input string, matching with a reversed regex, and then reversing the matches. This process can be implemented as follows:
const reverse = s => s.split('').reverse().join(''); const test = (stringToTests, reversedRegexp) => stringToTests .map(reverse) .forEach((s,i) => { const match = reversedRegexp.test(s); console.log(stringToTests[i], match, 'token:', match ? reverse(reversedRegexp.exec(s)[0]) : 'Ø'); });<p><strong>Examples</strong></p> <p>To illustrate its usage:</p> <ul><li>For the initial question mentioned in the context, the following regex would match 'm' in 'jim' or 'm', but not 'jam':</li></ul> <pre class="brush:php;toolbar:false">test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/)
test(['max-height', 'line-height'], /thgieh(?!(-enil))/)
The above is the detailed content of How Can I Implement Negative Lookbehind in JavaScript Regex?. For more information, please follow other related articles on the PHP Chinese website!