OMBD#11: Supercharge Your Regex With the Negative Lookahead Assertion
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.
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
https results in undesired
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:
- 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
Here’s a demo on RegExr.
So our solution would be:
If you liked this story, you may also like:
1 Minute To Become A Better Developer (#10)
Learn how to change public your public IP address, in one minute.
1 Minute To Become A Better Developer (#12)
Learn how to leverage window.IntersectionObserver to find out how many visitors see your content, in one minute.