DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Positive And Negative Lookahead

  • Lookaheads are patterns that tell JavaScript to look-ahead in your string to check for patterns further along. This can be useful when you want to search for multiple patterns over the same string.
  • There are two kinds of lookaheads: positive lookahead and negative lookahead.
  • A positive lookahead will look to make sure the element in the search pattern is there, but won't actually match it. A positive lookahead is used as (?=...) where the ... is the required part that is not matched.
  • A negative lookahead will look to make sure the element in the search pattern is not there. A negative lookahead is used as (?!...) where the ... is the pattern that you do not want to be there. The rest of the pattern is returned if the negative lookahead part is not present.

  • Lookaheads are a bit confusing but let me show you an example:
    A more practical use of lookaheads is to check two or more patterns in one string. Here we changed the pwRegex to match passwords that are greater than 5 characters long, and have two consecutive digits.

    let sampleWord = "astronaut";
    let pwRegex = /(?=\w{6,})(?=\D+\d\d)/; 
    let result = pwRegex.test(sampleWord);
    
console.log(result); will display false
Enter fullscreen mode Exit fullscreen mode
let sampleWord = "bana12";
console.log(result); here it will display true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)