I have a url like http://www.example.com/blah/th.html
I need a javascript function to give me the \'th\' value from that.
All my urls have the same format (2
Using jQuery with the URL plugin:
var file = jQuery.url.attr("file");
var fileNoExt = file.replace(/\.(html|htm)$/, "");
// file == "th.html", fileNoExt = "th"
those will not work for lenghty url like
"/my/folder/questions.html#dssddsdsd?toto=33&dududu=podpodpo"
here I expect to get "questions.html". So a possible (slow) solution is as below
fname=function(url)
{ return url?url.split('/').pop().split('#').shift().split('?').shift():null }
then you can test that in any case you get only the filename.
fname("/my/folder/questions.html#dssddsdsd?toto=33&dududu=podpodpo")
-->"questions.html"
fname("/my/folder/questions.html#dssddsdsd")
-->"questions.html"
fname("/my/folder/questions.html?toto=33&dududu=podpodpo")
"-->questions.html"
(and it works for null)
(I would love to see a faster or smarter solution)
Similar to the others, but...I've used Tom's simple script - a single line,
then you can use the filename var anywhere:
http://www.tomhoppe.com/index.php/2008/02/grab-filename-from-window-location/
var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1);
var filename = url.split('/').pop()
A regex solution which accounts for URL query and hash identifier:
function fileNameFromUrl(url) {
var matches = url.match(/\/([^\/?#]+)[^\/]*$/);
if (matches.length > 1) {
return matches[1];
}
return null;
}
JSFiddle here.
This answer only works in browser environment. Not suitable for node.
function getFilename(url) {
const filename = decodeURIComponent(new URL(url).pathname.split('/').pop());
if (!filename) return 'index.html'; // some default filename
return filename;
}
function filenameWithoutExtension(filename) {
return filename.replace(/^(.+?)(?:\.[^.]*)?$/, '$1');
}
Here are two functions:
For parsing URL, new an URL
object should be the best choice. Also notice that URL do not always contain a filename.
Notice: This function try to resolve filename from an URL. But it do NOT guarantee that the filename is valid and suitable for use:
:
in windows, \0
in most OS, ...);CON
in windows);Test it out:
function getFilename(url) {
const filename = decodeURIComponent(new URL(url).pathname.split('/').pop());
if (!filename) return 'index.html'; // some default filename
return filename;
}
function test(url) {
console.log('Filename: %o\nUrl: %o', getFilename(url), url);
}
test('http://www.example.com');
test('http://www.example.com/');
test('http://www.example.com/name.txt');
test('http://www.example.com/path/name.txt');
test('http://www.example.com/path/name.txt/realname.txt');
test('http://www.example.com/page.html#!/home');
test('http://www.example.com/page.html?lang=en&user=Aan9u/o8ai#top');
test('http://www.example.com/%E6%96%87%E4%BB%B6%E5%90%8D.txt')