JavaScript - Get Filename and Extension from URL
Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
-
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
Posts:186
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: https://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
- Display message to every minute in Javascript
JavaScript - jQuery - Ajax
First post
Hello,
On eatch minute from the current hour I wanna have an message
I can not find out how to complete
I hope to get something like this (code...
Last post
If you only want to display a message to every minute, just use the setInterval() function. It calls a function repeatedly, over and over again, at...
- Hour and Minutes togheter in Javascript
JavaScript - jQuery - Ajax
First post
Dear Coursesweb I can not find out how to add the hours + minutes togheter.
<SCRIPT LANGUAGE= JavaScript >
day = new Date()
hr =...
Last post
See and use the following example:
<script>
var day = new Date();
let hr = day.getHours();
let mn = day.getMinutes();
let se =...