Using Regular Expressions to Append Specific Strings After Image URL Extensions .jpeg .jpg .png
Tadashi Shigeoka · Thu, June 1, 2017
I’ll introduce a regular expression to append .webp to the end of image URLs with extensions .jpeg .jpg .png.
Sample Code to Append Strings After Extensions Using Regular Expressions
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.
Reference Information
- String.prototype.replace() - JavaScript | MDN
- WebP – Webを速くするためにGoogleがやっていること Make the Web Faster 01 – | HTML5Experts.jp
That’s all from the Gemba.