Using Regular Expressions to Append Specific Strings After Image URL Extensions .jpeg .jpg .png
I’ll introduce a regular expression to append .webp to the end of image URLs with extensions .jpeg .jpg .png.
Here’s sample JavaScript code that uses regular expressions to append the string .webp after file extensions:
The key point is that it properly considers URL parameters like ?v=123.
var regExp = /(\\.jpeg|\\.jpg|\\.png)/;
var str = "http://example.com/sample.jpeg?v=123";
var newstr = str.replace(regExp, "$1\\.webp");
console.log(newstr); // http://example.com/sample.jpeg.webp?v=123
var str = "http://example.com/sample.jpg?v=123";
var newstr = str.replace(regExp, "$1\\.webp");
console.log(newstr); // http://example.com/sample.jpg.webp?v=123
var str = "http://example.com/sample.png?v=123";
var newstr = str.replace(regExp, "$1\\.webp");
console.log(newstr); // http://example.com/sample.png.webp?v=123
For example, when implementing WebP support, you need to write application code that displays WebP format only for Chrome browsers. In such cases, I hope the regular expression snippet introduced here will be useful.
That’s all from the Gemba.