Image URLs with query strings aren't matched
Closed this issue · 2 comments
This was originally reported as a bug on WordPress.org. It looks like if an image has a query string appended to the end of it, our current matching pattern won't catch the URL as being an image link. In order to work around this, I think we'd need to strip the query string before testing our URLs.
My main hesitation here is adding more regex on what's already a pretty wide-reaching search. I think the following JS would do the job, but I'll need to do some testing on both the actual matching as well as any possible performance issues.
/**
* Strips query strings and hash elements from a given string.
*
* @since 0.2.1
* @return string
*/
function stripQuery( index, element ) {
return element.replaceAll( ( '(\\?.*|\\#.*)' ), '' );
}
/**
* Checks href targets to see if a given anchor is linking to an image.
*
* @since 0.1.0
* @return mixed
*/
function testImages( index, element ) {
var $href = $( element ).attr( 'href' ).toLowerCase();
return /(png|jpg|jpeg|gif|tiff|bmp)$/.test( stripQuery( $href ) );
}
This also looks like it would probably do the job without regex:
/**
* Checks href targets to see if a given anchor is linking to an image.
*
* @since 0.1.0
* @return mixed
*/
function testImages( index, element ) {
return /(png|jpg|jpeg|gif|tiff|bmp)$/.test(
$( element ).attr( 'href' ).toLowerCase().split( '?' )[0].split( '#' )[0]
);
}
I'm guessing this would probably be better performance-wise, but again testing is needed.
This is fixed and seems to be working as expected. Closing this out, but may open another issue for performance at some point.