How to pull url file extension out of url string using javascript

Viewed 47037

How do I find the file extension of a URL using javascript? example URL:

http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294

I just want the 'swf' of the entire URL. I need it to find the extension if the url was also in the following format

http://www.adobe.com/products/flashplayer/include/marquee/design.swf

Obviously this URL does not have the parameters behind it.

Anybody know?

Thanks in advance

14 Answers
url.split('?')[0].split('.').pop()

usually #hash is not part of the url but treated separately

You can use the (relatively) new URL object to help you parse your url. The property pathname is especially useful because it returns the url path without the hostname and parameters.

let url = new URL('http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294');
// the .pathname method returns the path
url.pathname; // returns "/products/flashplayer/include/marquee/design.swf"
// now get the file name
let filename = url.pathname.split('/').reverse()[0]
// returns "design.swf"
let ext = filename.split('.')[1];
// returns 'swf'

This method works fine :

function getUrlExtension(url) {
  try {
    return url.match(/^https?:\/\/.*[\\\/][^\?#]*\.([a-zA-Z0-9]+)\??#?/)[1]
  } catch (ignored) {
    return false;
  }
}

function ext(url){
    var ext = url.substr(url.lastIndexOf('/') + 1),
        ext = ext.split('?')[0],
        ext = ext.split('#')[0],
        dot = ext.lastIndexOf('.');

    return dot > -1 ? ext.substring(dot + 1) : '';
}

If you can use npm packages, File-type is another option.

They have browser support, so you can do this (taken from their docs):

const FileType = require('file-type/browser');

const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';

(async () => {
    const response = await fetch(url);
    const fileType = await FileType.fromStream(response.body);

    console.log(fileType);
    //=> {ext: 'jpg', mime: 'image/jpeg'}
})();

It works for gifs too!

const getUrlFileType = (url: string) => {
  const u = new URL(url)
  const ext = u.pathname.split(".").pop()
  return ext === "/"
    ? undefined
    : ext.toLowerCase()
}
Related