bradxr
8/4/2018 - 9:00 PM

Positive and Negative Lookahead

Lookaheads are patterns that tell JavaScript to "look ahead" in the string to check for patterns further along There are positive lookaheads and negative lookaheads Positive - make sure the element is there but won't match it - (?=...) where the ... is the required part that is not matched Negative - make sure the element is not there - (?!...) where ... is the pattern that you don't want to be there, pattern is returned if negative lookahead part is not present

let quit = "qu";
let noquit = "qt";

let quRegex = /q(?=u)/;
let qRegex = /q(?!u)/;

quit.match(quRegex);    // returns ["q"]
noquit.match(qRegex);     // returns ["q"]


// check for two or more patterns in one string
// the below looks for between 3 and 6 characters and at least 1 number
let password = "abc123";
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password);   // returns true