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