Lookaheads - please help me understand the solution

Tell us what’s happening:

At the bottom of this post is one of my many attempts to figure out the code before I finally gave up and looked at the solution:


To which I have the following questions:

  1. Why is ^\D outside of the lookaheads? I had ^\D in one of my attempts but it had never occurred to me (nor do I think it would ever have) to move it outside.
  2. Why is there no $ at the end? Is it because of the asterisk, which represents any number of alphanumeric characters, so it’s only logical that the two digits at the end must represent the final ones? Why does adding $ at the end break the code?

Your code so far

let sampleWord = "astronaut";
let pwRegex = /(?=^[A-Za-z]{6,})(?=\d{2,}$); // Change this line
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/84.0.4147.105 Safari/537.36.

Challenge: Positive and Negative Lookahead

Link to the challenge:

Hey, not a fully fledged answer but some ideas:

  1. There is no need to look ahead if it’s a claim about first digit. Nor it is when referring to the end of a string. Look aheads are for something we may imagine as a cloud, we don’t have any index.

Example: ‘x contains 4numbers followed by a letter’, but where?! we don’t know, and we don’t care as long as they are there. So use lookahead.

  1. The money sign is missing because there is no requirement for anything to be at the end:

match passwords that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits.

  1. This could be relevant:remember it’s using test, not match. So we’re not matching any string anyways.

Now about the lookahead, I wouldn’t worry that much. It’s only important to know those exist really.

For real, apart from the challenge, I haven’t used lookaheads again.

because lookaheads are zero width characters, that means that they check if those characters are present next, but the point in the string in which to check is not advanced
so, as they are 0-width, the only string that would pass would be a string of length 1, but to return true the lookaheads need to match something, which can’t do if there is the end of the string after them