Home >Web Front-end >JS Tutorial >How Can I Implement Negative Lookbehind in JavaScript Regex?

How Can I Implement Negative Lookbehind in JavaScript Regex?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 06:53:13449browse

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:

  • Positive lookbehind: (?<=...)
  • Negative lookbehind: (?

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]))/)
  • Another example, matching "max-height" but not "line-height":
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!

Statement:
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