JavaScript - Get Filename and Extension from URL

PloMar
Posts: 48

JavaScript - Get Filename and Extension from URL

Hello
How can I get the filename and extension from a variale with an URL address in JavaScript?
The URL can be any kind of webpage address; with or without ?query and #hash, for example:

Code: Select all

http://a.com/b/filename.ext http://a.com/b/filename.ext#hash http://a.com/b/filename.ext?query http://a.com/b/filename.ext?query#hash
Also, without extension

Code: Select all

http://a.com/b/filename http://a.com/b/filename#hash http://a.com/b/filename?query http://a.com/b/filename?query#hash
- I want to get separately the "filename" and "ext" (if exists).
Any code example or ideea?
Thanks.

MarPlo
Hi,
Just use the getFilename() function from this example:

Code: Select all

<script> function getFilename(url){ // returns an object with {filename, ext} from url (from: http://coursesweb.net/ ) // get the part after last /, then replace any query and hash part url = url.split('/').pop().replace(/\#(.*?)$/, '').replace(/\?(.*?)$/, ''); url = url.split('.'); // separates filename and extension return {filename: (url[0] || ''), ext: (url[1] || '')} } // Usage var url = 'http;//coursesweb.net/index.php?m=p#i123'; var ob_fm = getFilename(url); // object with: ob_fm.filename and ob_fm.ext // test console.log(url_file); // {filename: "index", ext: "php"} </script>

Similar Topics