admin管理员组

文章数量:1134247

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

.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

.swf

Obviously this URL does not have the parameters behind it.

Anybody know?

Thanks in advance

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

Share Improve this question asked Aug 9, 2011 at 13:53 CarlCarl 5411 gold badge4 silver badges3 bronze badges 1
  • Thanks, I managed to get exactly what I needed thanks to Alex. I slightly modified it to; fileExtension("adobe.com/products/flashplayer/include/marquee/…); function fileExtension(url){fileSplit = url.split('?')[0]; fileIndex = fileSplit.substr(fileSplit.lastIndexOf(".")+1); alert(fileIndex); }; works like a charm – Carl Commented Aug 9, 2011 at 15:40
Add a comment  | 

18 Answers 18

Reset to default 64
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

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];
}

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.

This is the answer:

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

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'
url.split('?')[0].split('.').pop()

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

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

  // 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);
  }

This method works fine :

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

const getUrlFileType = (url: string) => {
  const u = new URL(url)
  const ext = u.pathname.split(".").pop()
  return ext === "/"
    ? undefined
    : ext.toLowerCase()
}
    var doc = document.location.toString().substring(document.location.toString().lastIndexOf("/"))
    alert(doc.substring(doc.lastIndexOf(".")))
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!

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.

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));
})();

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

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

What has been added?

  • Full removal of URL query if it exists before any other processing to avoid incorrect results as much as possible.

  • Support for multiple periods in a filename, for example: https://www.example.com/abcd.xrg.css or https://www.example.com/adbc.efg.cghf.js

  • Fix the trailing slash in the URL after the filename, as shown in the example: https://www.example.com/abcd.xrg.css/?hjh=1

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

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

本文标签: How to pull url file extension out of url string using javascriptStack Overflow