OMBD#11: Supercharge Your Regex With the Negative Lookahead Assertion

Make faster refactors in JavaScript, VSCode, or in your favourite place to run regular expressions

Jon Portella
2 min readMar 9, 2021

Welcome to issue #11 of One Minute Better Developer, where you become a more successful software developer by reading short nuggets of knowledge, one minute at a time.

🔛 ⏭️

Art by my buddy Loor Nicolas

THE PROBLEM

We have a list of images, some of them being requested via the HTTP protocol and some others via the HTTPS protocol.

A list of images with mixed HTTP and HTTPS.

We want all of them to use HTTPS.

How can we accomplish this? Just replacing http for https results in undesired httpss .

Just replacing http for https produces httpss.

So we only want to match and update http that is not followed by an s . How do we do that?

A SOLUTION

Enter Regex’s Negative Lookahead. The syntax is simple:

http(?!s)

Where:

  • The parentheses followed by a question mark and exclamation point (?!) is the construct for the Negative Lookahead.
  • Characters between the exclamation point and the closing parentheses are the ones negated. In this case, we are only negating the character s .

Here’s a demo on RegExr.

So our solution would be:

Using Regex’s Negative Lookahead, we can match http and not https.

--

--

Jon Portella

Software Engineer @ Pinterest - Teacher, maker, and general things do-er. - https://www.linkedin.com/in/jonportella/ - Toronto, Canada