A Positive Lookahead — JavaScript Beginnings

Theracode
Webtips
Published in
2 min readSep 16, 2021
Photo by Martin Shreder on Unsplash

Here’s how it happened. This article begins as an impulsive decision. “Why not give writing a Medium article a try?”, I thought to myself on a Wednesday. After all, I’ve read one or two Medium articles after a general Google search that others have posted online. I figured I might as well write about my own journey to become a better programmer.

Take what you will out of it, in any case, however, I hope you enjoy the read.

What I learned

Today I’m learning about lookaheads. Lookaheads in JavaScript (JS) are patterns that tell JS to look-ahead in your string for patterns further along. For example, you can use lookaheads to check if there are two or more patterns over the same string. I learned about two types of lookaheads.

First, I learned about positive lookaheads. Positive lookaheads are easy to understand. A positive lookahead will look to make sure the element in the search pattern is there. However, a positive lookahead will not actually match the element in the search pattern.

A positive lookahead: (?=xyz), where xyz is the placeholder for the necessary part that is not matched.

Second, I learned about negative lookaheads. Negative lookaheads are the opposite of positive lookaheads. A negative lookahead will look to make sure the element in the search pattern is not there.

A negative lookahead: (?!xyz), where xyz is the placeholder for the pattern you do not want there.

Let's try with an example:

let test1 = "hi"
let test2 = "h1"
let positiveRegex = /q(?=i)/;
let negativeRegex = /q(?!i)/;
test1.match(positiveRegex);
test2.match(negativeRegex);

Any idea what the match calls would return? If you guessed it right, both match calls would return with [“q”].

--

--