Challenge: Positive and Negative Lookahead

Tell us what’s happening:

Hi all - first post here, and before anything I want to give a very big thank you to the freeCodeCamp team for creating such a fantastic site for learning coding, free of charge!

I was having trouble with Regex lookaheads. As you can see below the only difference between my code and the solution was \D vs \w, and my code wouldn’t match “astr1on11aut”.

I was typing up this post asking for help but halfway through this, something occurred to me and, after some paying around, I think I figured out where the issue was:

A positive lookahead will look to make sure the element in the search pattern is there, but won’t actually match it.

“Won’t actually match it” seems to suggest that if multiple forward lookaheads are chained together, they will search for patterns as if the other lookaheads don’t exist, because nothing is matched. A further implication seems to be that the order of the chained together lookaheads won’t matter.

Initially I glanced over the “won’t actually match it” bit without really thinking about what it meant, and oh boy isn’t it easy to miss crucial details sometimes!

I thought I should still finish typing up this post in case anyone else is also confused by Regex lookaheads.

Or, just a friendly suggestion to freeCodeCamp, perhaps include a bit more clarification and emphasis on what “won’t match it” means? After working through this challenge, I feel this is arguably the most important feature of lookaheads.

Your code so far

let sampleWord = "astronaut";
let pwRegex = /^\D(?=\w{5})(?=\D*\d{2})/; // My code
//let pwRegex = /^\D(?=\w{5})(?=\w*\d{2})/; // Solution
let result = pwRegex.test(sampleWord);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 Edg/86.0.622.69.

Challenge: Positive and Negative Lookahead

Link to the challenge:

it means that the index at which the search is done doesn’t change, and you will not see what is inside the lookahead in the result if you use the match method

you could say that lookaheads match a position, if you have more than one, they all look that the string after that position satisfy them, and it also needs to satisfy all of them

consecutive lookaheads all look from same position, and all need to be satisfied

1 Like