Skip to main content

Archive

Show more

How to get file extension using javascript

how-to-get-file-extension-using-javascript


Question: How to get file extension using javascript

Answer: We have solved this question in two way, first way is not to check 'url' you can check 'image', 'document' etc. But second method is use to check 'url', 'image', 'document' etc. let's see both methods one by one


First: This method is work only for 'image' and 'document' files.

function getExtension(path) {
  var basename = path.split(/[\\/]/).pop(),  
      indexNum = basename.lastIndexOf(".");       

  if (basename === "" || indexNum < 1)      
      return "";                      

 return basename.slice(indexNum + 1);     
}

console.log( getExtension("Rustcode.web") );

Output:

".web"


Second: This is work for 'url', 'image' and 'document' files.

function getExtension(file) {
  var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i;
  var extension = file.match(regexp);
  return extension && extension[1];
}


console.log(getExtension("https://www.rustcodeweb.com"));
console.log(getExtension("https://www.rustcodeweb.com/2021/03"));
console.log(getExtension("https://www.rustcodeweb.com/p/about.html"));
console.log(getExtension("https://www.rustcodeweb.com/p/contact.html?mno=0123456789"));

Output:

"com"
"null"
"html"
"html"


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments