diff --git a/packages/block-editor/src/components/link-control/is-url-image.js b/packages/block-editor/src/components/link-control/is-url-image.js index bd7eabcdd5db4..34c0539663312 100644 --- a/packages/block-editor/src/components/link-control/is-url-image.js +++ b/packages/block-editor/src/components/link-control/is-url-image.js @@ -4,6 +4,7 @@ * @return {boolean} true if the url is an image url. */ export default function isImageUrl( url ) { - const pattern = /(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png)/g; + const pattern = + /^(https?:\/\/)([\w-]+(?:\.[\w-]+)*\/)*[\w-]+\.(?:jpg|JPG|jpeg|gif|png|webp)$/i; return pattern.test( url ); } diff --git a/packages/block-editor/src/components/link-control/test/is-url-image.js b/packages/block-editor/src/components/link-control/test/is-url-image.js new file mode 100644 index 0000000000000..14cf8a80f6144 --- /dev/null +++ b/packages/block-editor/src/components/link-control/test/is-url-image.js @@ -0,0 +1,28 @@ +/** + * Internal dependencies + */ +import isImageUrl from '../is-url-image'; + +describe( 'isImageUrl', () => { + // use .each to test multiple cases + it.each( [ + [ true, 'https://example.com/image.jpg' ], + [ true, 'https://example.com/image.gif' ], + [ true, 'https://example.com/image.png' ], + [ true, 'https://example.com/image.webp' ], + [ true, 'https://example.com/image.jpeg' ], + [ true, 'https://example.com/image.JPG' ], + [ false, 'https://example.com/image.txt' ], + [ false, 'https://example.com/image' ], + [ false, 'https://example.com/image.jpg?query=123' ], + [ false, '' ], + [ false, null ], + [ false, undefined ], + [ false, 123 ], + ] )( + 'returns %s when testing against URL "%s" for a valid image', + ( expected, testString ) => { + expect( isImageUrl( testString ) ).toBe( expected ); + } + ); +} );