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.
⏮️ 🔛 ⏭️
THE PROBLEM
We have a list of images, some of them being requested via the HTTP protocol and some others via the HTTPS protocol.
We want all of them to use HTTPS.
How can we accomplish this? Just replacing http
for https
results in undesired 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: