Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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


Solution 2:

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

Solution 3:

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.


Solution 4:

This is the answer:

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

Solution 5:

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


Post a Comment for "How To Pull Url File Extension Out Of Url String Using Javascript"