March 09, 2021 • 3 min read
We have a list of images, some of them being requested via the HTTP protocol and some others via the HTTPS protocol.
const string = `
<img src="https://via.placeholder.com/150">
<img src="https://via.placeholder.com/200">
<img src="http://via.placeholder.com/250">
<img src="https://via.placeholder.com/300">
<img src="http://via.placeholder.com/350">
`;
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.
const string = `
<img src="https://via.placeholder.com/150">
<img src="https://via.placeholder.com/200">
<img src="http://via.placeholder.com/250">
<img src="https://via.placeholder.com/300">
<img src="http://via.placeholder.com/350">
`;
const updatedString = string.replaceAll(/http/g, "https");
console.log(updatedString);
// <img src="httpss://via.placeholder.com/150">
// <img src="httpss://via.placeholder.com/200">
// <img src="https://via.placeholder.com/250">
// <img src="httpss://via.placeholder.com/300">
// <img src="https://via.placeholder.com/350">
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:
(?!) is the construct for the Negative Lookahead.s .Here’s a demo on RegExr.
So our solution would be:
const string = `
<img src="https://via.placeholder.com/150">
<img src="https://via.placeholder.com/200">
<img src="http://via.placeholder.com/250">
<img src="https://via.placeholder.com/300">
<img src="http://via.placeholder.com/350">
`;
const updatedString = string.replaceAll(/http(?!s)/g, "https");
console.log(updatedString);
// <img src="https://via.placeholder.com/150">
// <img src="https://via.placeholder.com/200">
// <img src="https://via.placeholder.com/250">
// <img src="https://via.placeholder.com/300">
// <img src="https://via.placeholder.com/350">
Using Regex’s Negative Lookahead, we can match http and not https.