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.
Posts: 48

JavaScript - Get Filename and Extension from URL

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
Also, without extension

Code: Select all
- I want to get separately the "filename" and "ext" (if exists).
Any code example or ideea?

Just use the getFilename() function from this example:

Code: Select all

function getFilename(url){
  // returns an object with {filename, ext} from url (from: )

  // 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;//';
var ob_fm = getFilename(url);  // object with:  ob_fm.filename and ob_fm.ext

// test
console.log(url_file);  //  {filename: "index", ext: "php"}

Similar Topics