Carl
Carl

Reputation: 541

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

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

Upvotes: 54

Views: 68359

Answers (18)

This is an improved version of Yuval A's answer.

What has been added?

const getExtension = (url) => {
    // If queries are present, we removed them from the URL.
    // If there is any trailing slash, we remove it from the URL.
    if (url.includes('?')) {
        url = url.replace(/[?&]+([^=&]+)=([^&]*)/gi,'')?.replace(/\/+$/gi,'');
    }
    // Extension starts after the first dot after the last slash
    let extStart = url.indexOf('.',url.lastIndexOf('/')+1);
    if (extStart == -1) {
        return false; 
    }
    var ext = url.substr(extStart+1);
    // To handle multiple periods in the filename, we ensure that the current dot is the final one.
    if ( (extStart = url.lastIndexOf('.')) ) {
        ext = url.substr(extStart+1);
    }
    // end of extension must be one of: end-of-string or question-mark or hash-mark with ext.search(/$|[?#]/)
    return ext.substring(0,ext.search(/$|[?#]/));
};

console.log(getExtension('https://cdn.sstatic.net/Js/third-party/npm/@stackoverflow/stacks/dist/js/stacks.min.js?v=d5f780ae3281')); 
//Results: js

console.log(getExtension('https://cdn.sstatic.net/Js/third-party/npm/@stackoverflow/stacks/dist/js/stacks.min..gz.js?v=d5f780ae3281')); 
//Results: js

console.log(getExtension('https://cdn.sstatic.net/Js/third-party/npm/@stackoverflow/stacks/dist/js/stacks.min.gz.js/?v=d5f780ae3281')); 
//Results: js

console.log(getExtension('https://cdn.sstatic.net/Js/third-party/npm/@stackoverflow/stacks/dist/js/stacks.js/?v=d5f780ae3281')); 
//Results: js

Upvotes: 0

he2lium
he2lium

Reputation: 1

You can use regex like this or modify it for your goal.

I hope it will help you because I can't find better solution and make up it.

function getExtensionFromURL(URL){
  const tokens = URL.match(/(\.[a-zA-Z0-9]+(\?|\#|$))/g) 
  if(!tokens[0]) return false 
  return tokens[0].replace(/[^A-Za-z0-9\.]/g,'') 
}
console.log(getExtensionFromURL("https://ya.com/sjsjs/text-ee/image.jpeg/target.png?q=tail&w=force"))
// .png
console.log(getExtensionFromURL("https://ya.com/sjsjs/text-ee/image.jpeg/target.png#fff=eee")) 
// .png
console.log(getExtensionFromURL("https://ya.com/sjsjs/text-ee/image.jpeg/target.png"))
// .png

Screenshot from regex101

Upvotes: 0

Safyan Akram
Safyan Akram

Reputation: 9

If you wanna use this solution. these packages are using latest import/export method. in case you wanna use const/require bcz your project is using commonJS you should downgrade to older version.

i used "got": "11.8.5","file-type": "16.5.4",

const FileType = require('file-type');
const got = require('got');

const url ='https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
    const stream = got.stream(url);

    console.log(await FileType.fromStream(stream));
})();

Upvotes: 0

AmerllicA
AmerllicA

Reputation: 32747

Actually, I like to imporve this answer, it means my answer will support # too:

const extExtractor = (url: string): string =>
  url.split('?')[0].split('#')[0].split('.').pop() || '';

This function returns the file extension in any case.

Upvotes: 0

Damian
Damian

Reputation: 608

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

Upvotes: 2

gray
gray

Reputation: 1018

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!

Upvotes: 0

smarteist
smarteist

Reputation: 1421

This method works fine :

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

Upvotes: 4

gzzz
gzzz

Reputation: 368

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) : '';
}

Upvotes: 0

T.Todua
T.Todua

Reputation: 56557

function get_url_extension( url ) {
    return url.split(/[#?]/)[0].split('.').pop().trim();
}

example:

get_url_extension('https://example.com/folder/file.jpg');
get_url_extension('https://example.com/fold.er/fil.e.jpg?param.eter#hash=12.345');

outputs ------> jpg

Upvotes: 64

svarog
svarog

Reputation: 9847

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'

Upvotes: 6

OZZIE
OZZIE

Reputation: 7388

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

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

Upvotes: 5

coderexe
coderexe

Reputation: 1

var fileExtension = function( url ) {
    var length=url.split(?,1);
    return length
}
document.write("the url is :"+length);

Upvotes: -2

Alex K.
Alex K.

Reputation: 175956

For the extension you could use this function:

function ext(url) {
    // Remove everything to the last slash in URL
    url = url.substr(1 + url.lastIndexOf("/"));

    // Break URL at ? and take first part (file name, extension)
    url = url.split('?')[0];

    // Sometimes URL doesn't have ? but #, so we should aslo do the same for #
    url = url.split('#')[0];

    // Now we have only extension
    return url;
}

Or shorter:

function ext(url) {
    return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('#')[0].substr(url.lastIndexOf("."))
}

Examples:

ext("design.swf")
ext("/design.swf")
ext("http://www.adobe.com/products/flashplayer/include/marquee/design.swf")
ext("/marquee/design.swf?width=792&height=294")
ext("design.swf?f=aa.bb")
ext("../?design.swf?width=792&height=294&.XXX")
ext("http://www.example.com/some/page.html#fragment1")
ext("http://www.example.com/some/dynamic.php?foo=bar#fragment1")

Note: File extension is provided with dot (.) at the beginning. So if result.charat(0) != "." there is no extension.

Upvotes: 12

Yuval A.
Yuval A.

Reputation: 6099

  // Gets file extension from URL, or return false if there's no extension
  function getExtension(url) {
      // Extension starts after the first dot after the last slash
      var extStart = url.indexOf('.',url.lastIndexOf('/')+1);
      if (extStart==-1) return false;
      var ext = url.substr(extStart+1),
          // end of extension must be one of: end-of-string or question-mark or hash-mark
          extEnd = ext.search(/$|[?#]/);
      return ext.substring (0,extEnd);
  }

Upvotes: 4

Adam
Adam

Reputation: 5253

This is the answer:

var extension = path.match(/\.([^\./\?]+)($|\?)/)[1];

Upvotes: 7

iConnor
iConnor

Reputation: 20209

Something like this maybe?

var fileName = 'http://localhost/assets/images/main.jpg';

var extension = fileName.split('.').pop(); 

console.log(extension, extension === 'jpg');

The result you see in the console is.

jpg true

if for some reason you have a url like this something.jpg?name=blah or something.jpg#blah then you could do

extension = extension.split(/\#|\?/g)[0];

drop in

var fileExtension = function( url ) {
    return url.split('.').pop().split(/\#|\?/)[0];
}

Upvotes: 25

Federico Lebrón
Federico Lebrón

Reputation: 1802

Take a look at regular expressions. Specifically, something like /([^.]+.[^?])\?/.

Upvotes: 4

ek_ny
ek_ny

Reputation: 10243

    var doc = document.location.toString().substring(document.location.toString().lastIndexOf("/"))
    alert(doc.substring(doc.lastIndexOf(".")))

Upvotes: 1

Related Questions