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

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

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?

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.

Full-Stack Developer, Teacher, Maker, and general Things-Doer. https://www.linkedin.com/in/jonportella/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store