Home > Software engineering >  How to find the given image source (url) is in svg format?
How to find the given image source (url) is in svg format?

Time:02-02

I am getting images as URLs from my CMS provider like this

SVG image src URL:

https://images.ctfassets.net/nnigwk0legme/5GFugE0snFGK58YdGi1dLh/993cca13e1e6b4a9b55bad39c247b6e5/CLA_Logo.svg

Here I am getting images in different formats like png, jpeg, jpg, SVG, etc... In this, I need to find the images only in SVG format.

I planned to create a utility function and going to pass all the image URLs to it. It will return true only if the image is in SVG format else it will return false.

Is there any way I can do this in Javascript (ReactJS)? If any source or plugin is available. Please share that.

Will this function work ?


function isSvgFormatImage(url) {
  return url.split('.').includes('svg')
}

Thanks in advance

CodePudding user response:

If the url ends in ".svg", this function returns true

function isSvgFormat (url){
   return url.endsWith(".svg")
}

CodePudding user response:

Yes, your function would work, one a little more efficient would be:

/**
 * @param {string} url
 */
function isSVGFormatImage(url) {
  return url.endsWith(".svg");
}

// Some test cases

console.assert(isSVGFormatImage("https://example.com/another.svg") === true);

console.assert(isSVGFormatImage("https://example.com/svg.png") === false);

console.assert(isSVGFormatImage("https://example.com/file.jpg") === false);

  •  Tags:  
  • Related