This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Javascript Regular Expressions: Find a String that Precedes Another String

1:27 JavaScript lesson by

Lookaheads allow us to match a pattern followed by another pattern without including the second pattern in our match.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Lookaheads allow us to match a pattern followed by another pattern without including the second pattern in our match.

If we wanted to match a pattern that's followed by another pattern but we don't want to include that second pattern in our match, we can use something called a lookahead. I'm going to have just our standard foo, foobar, foobas, and fooboo. Then, in our regx, we are going to set up...

Let's go ahead and first capture foo. We know how to do that. We've captured all the foos. We also know that we can use a capturing group to capture foobar or fooboo. Now, we're capturing both foobar and fooboo.

Let's say that we want that result, but we only want to capture foo where it's followed by bar or boo. What we can do is use a lookahead. Right here in our capture group, we do ?=. Save that. You can see that we've actually captured foo where it was followed by bar, and we've captured foo where it was followed by boo.

We can also do a negative lookahead. Where this is a positive lookahead, meaning we are expecting it to follow the preceding pattern, we can do a negative lookahead, with a ? and !, which means we want to capture foo where it's not followed by bar or boo.

Save that, and we can see we've captured foo here, where it's not followed by bar or boo, and foo here, where it's followed by bas, which clearly is not bar or boo.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?