js function to get filename from url
Asked Answered
K

26

95

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 letter filenames, with .html extension).

I want it to be a safe function, so if someone passes in an empty url it doesn't break.

I know how to check for length, but I should be checking for null to right?

Kruller answered 4/2, 2009 at 15:11 Comment(2)
Possible duplicate of How to get the file name from a full path using JavaScript?Bentonbentonite
For something as specific as you want, you may use RegEx: https://mcmap.net/q/218266/-js-function-to-get-filename-from-urlKennethkennett
S
227
var filename = url.split('/').pop()
Scrotum answered 17/6, 2013 at 8:50 Comment(20)
By far the simplest and best answer.Manille
what if there are query parameters behind?Dromous
This also doesn't handle URL fragment IDs (i.e. # IDs)Sufferable
How about this: url.split('#').shift().split('?').shift().split('/').pop()Kenyettakenyon
@Kenyettakenyon your answer is the correct one : you have to start by cleaning # and ? and afterwards get split on / or you will get the / in querystring and anchorsBrieta
it is almost correct but won't work with http://domain/THE_PATH?firstParam=BLABLA/BLEBLE".split('/').pop()Shaunda
Not correct at all despite all upvotes! Miss a lot of points.. does not check if url is undefined ... does not split on '.' ... does not remove eventual query string ...Gumma
Even assuming no query string, path, fragment, whatever, doesn't this produce 'th.html' and not 'th', which was what the requester asked for?Corporator
How about this? new URL(url).pathname.split('/').pop();Procure
@Corporator You can add .split('.')[0] at the end. So the full line would be var filename = url.split('/').pop().split('#')[0].split('?')[0].split('.')[0];Frequent
@SangbokLee i guess what you are suggesting is what I implemented here in one of this post's answers.. you may see it here => https://mcmap.net/q/218266/-js-function-to-get-filename-from-urlShaunda
this solution actually doesn't strip query parameters nor anchors from the url i.ibb.co/c3SMNmS/image.png and actually may have some NOT correct results given some url without a path i.ibb.co/jJQ4CnC/image.png. It is a very simple solution that works for some cases.Shaunda
url.split('/').at(-1); ^-inspired by python slicing. ...and .at(-2); will give you the next-to-last elementChloe
@SangbokLee That approach has to be used like this, unless url is 100% guaranteed to been complied the URL format. And if that is guaranteed so, you will likely don't have to use this sort of code, in general. (_=>{try{return new URL(__url__).pathname.split('/').pop()}catch{return ''}})()Moira
@Shaunda You may see https://mcmap.net/q/98746/-last-segment-of-url-with-javascriptProcure
@SangbokLee That was intended. I originally wrote as (_=>{try{return new URL(url).pathname.split('/').pop()}catch{return ''}})() but added underscores for readability. You were wrong because it doesn't pass any parameter. If you really want to do so, this will be correct: (_=>{try{return new URL(_).pathname.split('/').pop()}catch{return ''}})(url) But I don't see any reason to do like this in a single line IIFE and even it's longer. You said you wouldn't care but you should do care especially when trying correct others and don't really have to try to dig some fault in others' advice.Moira
However we don't have to care about this anomore because there are simple and shorter codes which do the similar job: https://mcmap.net/q/218266/-js-function-to-get-filename-from-url - You can chose one in your favor. Allow or not relative URLs, ignore or not trailing slashes, do or don't some validity test. Have a nice 추석 holydays!Moira
@SangbokLee Oh, come on. What I originally wrote was not at all meaningful. The fact is you were just wrong. Don't you just understand that the above code should not be "corrected" according to your "wrong" suggestion? I said "You were wrong because it doesn't pass any parameter". I can't believe you still have no idea that your attempt to "correction" was wrong. And I doubt how preventing exception could be a "personal" thing. At the first, I said "unless url is 100% guaranteed to been complied the URL format". Do you really think that leaving expected errors uncaught is just personal flavor?Moira
@SangbokLee See who messed up comments section if you can do a "think". You started it by wrong suggestion in rude command tone. Did you thought I explained those because I just don't want to admit my mistake? Oh, well. Let's assume the placeholder is very important. So what? Nothing is changing. It's still same that what you wrote was just stupid nonsense. My example codelet would work fine without any modification, and what you suggested will break it from working. You really never have to know my original wrote to realize this. So shame on you.Moira
@Moira Okay, I've deleted my comments.Procure
M
107

Why so difficult?

= url.split('#')[0].split('?')[0].split('/').pop();

RegEx below would result same as the above's normally, but will return empty string if the URL was significantly malformed.

= (url.match(/^\w+:(\/+([^\/#?\s]+)){2,}(#|\?|$)/)||[])[2]||'';
// Returns empty string for relative URLs unlike the original approach

= (url.match(/^\w+:(\/+([^\/#?\s]+)){2,}/)||[])[2]||'';
// Ignores trailing slash (e.g., ".../posts/?a#b" results "posts")

All three of them would return file😃.name from:

  • my://host/path=&%dir///file😃.name?q=1/2&3=&#a/?b//?

The third one would also return dir.name from:

  • my://host/path=&%dir///dir.name/?not/these/#/ones//?

First Edit (Sep 2023) :

  • Changed processing order because RFC 3986 explicitly allows fragments to having unencoded slashes. Now it would handles fine even the query("search" in JS) includes unencoded slashes(which obviously had to be encoded).
  • This means it might properly handles any form of URLs that most browsers could recognize.
  • Using RegEx method was added which includes very basic validity test. Similar concept to the original one but using different approach.

Try to test your URL by enter below. The third one would ignores trailing slash as described the above code. Please comment if the RegEx ones wouldn't properly handle any valid URL

<style>*{margin:0;padding:0;box-sizing:border-box;border:none;}label{font-size:90%}input{display:block;margin:.2em auto 0;padding:.8em 1.2em;width:calc(100% - 5px);background:#f8f8f8;border-radius:1em;}p{margin-top:1.4em;padding-left:.5em;font-size:95%;color:#0008}p::after{content:attr(title);margin-left:.5em;padding:.4em .2em;background:#fe8;border-radius:.5em;font-weight:800;color:#000;}</style>
<label for="input">Enter your URL here:</label>
<input value="my://host/path=&%dir///file😃.name?q=1/2&3=&#a/?b//?" id="input">
<p>A</p>
<p>B</p>
<p>C</p>
<script>
((input = document.querySelector('input'), output = document.querySelectorAll('p')) => {
  const getFilename = _=> {
    output[0].title = input.value.split('#')[0].split('?')[0].split('/').pop();
    output[1].title = (input.value.match(/^\w+:(\/+([^\/#?\s]+)){2,}(#|\?|$)/)||[])[2]||'';
    output[2].title = (input.value.match(/^\w+:(\/+([^\/#?\s]+)){2,}/)||[])[2]||'';
  };
  getFilename();
  input.addEventListener('input', getFilename);
  input.select();
})();
</script>
Moira answered 20/4, 2016 at 22:56 Comment(10)
Nicely done. Handles presence or absence of # and/or ?.Sufferable
This should be the top answer.Bohun
@Kenyettakenyon gave a better answer on another comment : url.split('#').shift().split('?').shift().split('/').pop() You have to start by splitting on # and ? and afterwards split on / or you will catch the / parts of the anchor and querystring instead of the one from your path (which will typically lead to errors on amazon s3 protected urls )Brieta
What if URL doesn't actually has a filename in it? e.g: http://www.example.com this function will return "www.example.com" which is incorrect. It should be either empty string or null.Hilly
Won't work for "http://www.example.com/filenam.zip?passkey=1/2"Banquette
@Banquette (and Slava too) you are right, do note that other solutions works with those inputs as argument (like this one:https://mcmap.net/q/218266/-js-function-to-get-filename-from-url) but not this one. Although this was a good approach for reaching a solution.Shaunda
Recently I realized that non-encoded slashes and question marks are explicitly allowed within the fragment due to the RFC 3986. So yes, this won't properly handle some legit URLs and I will rewrite the code later. Thanks for the inform.Moira
@Banquette Use the version by @hayatbiralemAntlion
Or, use the super sexy version I just posted!Antlion
@tsh, systho, SlavaFominII, Victor, I fixed all those problems using RegEx while persisted at minimal. Please comment if the new one wouldn't handle any valid URL.Moira
R
31

Use the match function.

function GetFilename(url)
{
   if (url)
   {
      var m = url.toString().match(/.*\/(.+?)\./);
      if (m && m.length > 1)
      {
         return m[1];
      }
   }
   return "";
}
Ringtail answered 4/2, 2009 at 15:24 Comment(3)
This doesn't work if you have multiple multiple '.'s in the filenameTropopause
Does not remove query stringGumma
This will return the name of the file without it's extension.Corriecorriedale
B
16

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);
Bought answered 19/3, 2010 at 20:9 Comment(2)
Length is optional I believe: location.pathname.substr(location.pathname.lastIndexOf("/")+1)Tumbleweed
It shows a complete example for googlers like me - small improvement substr is deprecated.Kelso
T
15

In addition to the existing answers, I would recommend using URL() constructor (works both in browsers and Node.js) because you can be sure your URL is valid:

const url = 'https://test.com/path/photo123.png?param1=1&param2=2#hash';

let filename = '';
try {
  filename = new URL(url).pathname.split('/').pop();
} catch (e) {
  console.error(e);
}
console.log(`filename: ${filename}`);
Twinge answered 23/3, 2021 at 17:44 Comment(1)
With new built-in Array method we can do new URL(url).pathname.split('/').at(-1). .pop() still works tho.Immixture
S
12

This should work for all cases

function getFilenameFromUrl(url) {
  const pathname = new URL(url).pathname;
  const index = pathname.lastIndexOf('/');
  return pathname.substring(index + 1) // if index === -1 then index+1 will be 0
}
Shaunda answered 30/11, 2018 at 15:17 Comment(7)
Actually, this is the only solution working for all the edge cases I'm aware of. At least in the supported browsers (>89%).Hilly
Not in my browser! SyntaxError: Unexpected token ':'Gumma
Any solution with URL doesn't work for relative URLsDaddy
@DenisG.Labrecque you are right this solution doesn't works with "relative URL's" e.g.: questions/511761/js-function-to-get-filename-from-url/53560218?noredirect=1#comment111357776_53560218 as using that string the URL object won't be constructed because of an invalid URL as argument. This solution will work with a fully qualified URL or "absolute", i mean, the url must begin with a protocol. In that case you may add an "http://" or ("whatever://") prefix to the relative URL (thus it becomes absolute) and this code will work as a charm.Shaunda
Code golf fun: f=u=>(p=>(i=>-1!==i?p.substring(i+1):p)(p.lastIndexOf('/')))(new URL(u).pathname);Lamm
You can even omit the -1 !== index check and just write return pathname.substring(index + 1); since -1 + 1 will return 0.Registrar
@Registrar nice move!! updating snippet!Shaunda
S
8

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.

Sufferable answered 3/4, 2016 at 3:53 Comment(2)
This is the best answer when using regex.Socinus
What if URL doesn't actually has a filename in it? e.g: http://www.example.com this function will return "www.example.com" which is incorrect. It should be either empty string or null.Hilly
D
6

Because cases tend to fail with custom code, I looked up to the JavaScript URL class. Alas, it chokes on relative URLs! Also, it doesn't have a property to get the file name. Not epic.

There has to be a good library out there which solves this common problem. Behold URI.js. All you need is a simple statement like the following:

let file = new URI(url).filename()

Then we can create a simple function that does null checks and removes the file extension:

function fileName(url) {
   if (url === null || typeof url === 'undefined')
      return ''
   let file = new URI(url).filename() // File name with file extension
   return file.substring(0, file.lastIndexOf('.')) // Remove the extension
}

Here's a snippet with test cases to play around with. All cases pass except drive paths.

test('Dots in file name without URL', 'dotted.file.name.png', 'dotted.file.name')
test('Dots in file name with URL', 'http://example.com/file.name.txt', 'file.name')
test('Lengthy URL with parameters', '/my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo', 'filename')
test('URL with hash', '/my/folder/filename.html#dssddsdsd', 'filename')
test('URL with query strings', '/my/folder/filename.html?toto=33&dududu=podpodp', 'filename')
test('Hash after query string', 'http://www.myblog.com/filename.php?year=2019#06', 'filename')
 test('Query parameter with file path character', 'http://www.example.com/filename.zip?passkey=1/2', 'filename')
test('Query parameter with file path character and hash', 'http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top', 'filename')
test('Asian characters', 'http://example.com/文件名.html', '文件名')
test('URL without file name', 'http://www.example.com', '')
test('Null', null, '')
test('Undefined', undefined, '')
test('Empty string', '', '')
test('Drive path name', 'C:/fakepath/filename.csv', 'filename')

function fileName(url) {
   if (url === null || typeof url === 'undefined')
      return ''
   let file = new URI(url).filename() // File name with file extension
   return file.substring(0, file.lastIndexOf('.')) // Remove the extension
}

function test(description, input, expected) {
   let result = fileName(input)
   let pass = 'FAIL'
   if (result === expected)
      pass = 'PASS'
   console.log(pass + ': ' + description + ': ' + input)
   console.log('  =>  "' + fileName(input) + '"')
}
<script src="https://cdn.jsdelivr.net/gh/medialize/URI.js@master/src/URI.js"></script>

Results

PASS: Dots in file name without URL: dotted.file.name.png
  =>  "dotted.file.name"
PASS: Dots in file name with URL: http://example.com/file.name.txt
  =>  "file.name"
PASS: Lengthy URL with parameters: /my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo
  =>  "filename"
PASS: URL with hash: /my/folder/filename.html#dssddsdsd
  =>  "filename"
PASS: URL with query strings: /my/folder/filename.html?toto=33&dududu=podpodp
  =>  "filename"
PASS: Hash after query string: http://www.myblog.com/filename.php?year=2019#06
  =>  "filename"
PASS: Query parameter with file path character: http://www.example.com/filename.zip?passkey=1/2
  =>  "filename"
PASS: Query parameter with file path character and hash: http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top
  =>  "filename"
PASS: Asian characters: http://example.com/文件名.html
  =>  "文件名"
PASS: URL without file name: http://www.example.com
  =>  ""
PASS: Null: null
  =>  ""
PASS: Undefined: undefined
  =>  ""
PASS: Empty string: 
  =>  ""
FAIL: Drive path name: C:/fakepath/filename.csv
  =>  ""

This solution is for you if you're too lazy to write custom code and don't mind using a library to do work for you. It isn't for you if you want to code golf the solution.

Daddy answered 18/7, 2020 at 17:59 Comment(0)
S
5

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)

Stotinka answered 6/1, 2015 at 14:13 Comment(4)
Why do you expect to get "questions.html" when it is asked for get the name "questions" only?Gumma
Wrong. file extension is part of the name right? and it is asked filename right?Stotinka
See the second line in question: I need a javascript function to give me the 'th' value from that.Gumma
Ok, I missed it ;-) Then it is a onliner ie .split('.').pop()Stotinka
B
5

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:

  • first one get filename from url
  • second one get filename without extension from a full filename

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:

  • Some OS disallow certain character in filename (e.g. : in windows, \0 in most OS, ...);
  • Some filename may reserved by OS (e.g. CON in windows);
  • Some filename may make user unhappy to handle it (e.g. a file named "--help" in Linux)

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')
Banquette answered 1/2, 2018 at 3:30 Comment(10)
Why make it so complicated? It gets unsafe.Gumma
@PauliSudarshanTerho What do you mean by unsafe? Anything here is unsafe?Banquette
Simplicity = Safe. See my solution. Complexity = Unsafe.Gumma
@PauliSudarshanTerho But an answer should first be correct, then simple. And I can't see how simple = safe holds.Banquette
As you note some OS may have issues URL() and some browsers do not support it? Where is filenameWithoutExtension() used?Gumma
@PauliSudarshanTerho URL is browser specified, if you are using node.js, you may want some package which provide similar functions to it. Most recent browsers should support URL, but this may missing if you are working on old ones like IE. A filename contains special characters may not be valid on some OS, that's nothing to do with how to parse it (e.g. http://www.example.com/a|b.txt would be perfect valid URL. And a|b.txt would also be valid, but confusing, filename on Linux. But you cannot / should not name a file like this on Windows.Banquette
Sounds unsafe to me. How can I check "https://www.example.com/" or "https://www.example.com" give empty file name with your solution?Gumma
@PauliSudarshanTerho If so, you only need the first line, decodeURIComponent(new URL('http://www.example.com').pathname.split('/').pop()); will give you empty string as you expected.Banquette
I remember your advise: an answer should first be correct, then simple - Very good! We are right on different things, but sure you are right.. often safety may require more code.. fore example check on null and fixes of all kinds to not break. Devil is in the details.Gumma
This should be marked as the correct answer. +1 for using URL and +99 for decodeURIComponentAbsolve
T
3

I'd use the substring function combined with lastIndexOf. This will allow for filenames with periods in them e.g. given http://example.com/file.name.txt this gives file.name unlike the accepted answer that would give file.

function GetFilename(url)
{
    if (url)
    {
        return url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
    }
    return "";
}
Tropopause answered 6/1, 2013 at 13:5 Comment(0)
A
2

This should handle anything you throw at it (absolute URLs, relative URLs, complex AWS URLs, etc). It includes an optional default or uses a psuedorandom string if neither a filename nor a default were present.

function parseUrlFilename(url, defaultFilename = null) {
    let filename = new URL(url, "https://example.com").href.split("#").shift().split("?").shift().split("/").pop(); //No need to change "https://example.com"; it's only present to allow for processing relative URLs.
    if(!filename) {
        if(defaultFilename) {
            filename = defaultFilename;
        //No default filename provided; use a pseudorandom string.
        } else {
            filename = Math.random().toString(36).substr(2, 10);
        }
    }
    
    return filename;
}

Props to @hayatbiralem for nailing the order of the split()s.

Antlion answered 1/4, 2021 at 16:20 Comment(1)
probably one of the best answers i've seen on SO... reason saying that is thorough and intuitive for testingContiguous
G
1

Using jQuery with the URL plugin:

var file = jQuery.url.attr("file");
var fileNoExt = file.replace(/\.(html|htm)$/, "");
// file == "th.html", fileNoExt = "th"
Getz answered 4/2, 2009 at 19:17 Comment(0)
S
1

For node and browsers, based on @pauls answer but solving issues with hash and more defensive:

export function getFileNameFromUrl(url) {
  const hashIndex = url.indexOf('#')
  url = hashIndex !== -1 ? url.substring(0, hashIndex) : url
  return (url.split('/').pop() || '').replace(/[\?].*$/g, '')
} 

Few cases:

describe('getFileNameFromUrl', () => {

  it('absolute, hash and no extension', () => {
    expect(getFileNameFromUrl(
      'https://foo.bar/qs/bar/js-function-to-get-filename-from-url#comment95124061_53560218'))
    .toBe('js-function-to-get-filename-from-url')
  })

  it('relative, extension and parameters', () => {
    expect(getFileNameFromUrl('../foo.png?ar=8')).toBe('foo.png')
  })

  it('file name with multiple dots, hash with slash', () => {
    expect(getFileNameFromUrl('questions/511761/js-function.min.js?bar=9.9&y=1#/src/jjj?=9.9')).toBe('js-function.min.js')
  })
})
Shackleford answered 10/6, 2019 at 0:45 Comment(2)
It is not JavascriptGumma
http://www.example.com/page.html?lang=en&user=Aan9u/o8ai#topBanquette
D
0

Similarly to what @user2492653 suggested, if all you want is the name of the file like Firefox gives you, then you the split() method, which breaks the string into an array of components, then all you need to do it grab the last index.

var temp = url.split("//");
if(temp.length > 1)
 return temp[temp.length-1] //length-1 since array indexes start at 0

This would basically break C:/fakepath/test.csv into {"C:", "fakepath", "test.csv"}

Diplopia answered 11/9, 2013 at 18:19 Comment(0)
C
0

my 2 cents

the LastIndexOf("/") method in itself falls down if the querystrings contain "/"

We all know they "should" be encoded as %2F but it would only take one un-escaped value to cause problems.

This version correctly handles /'s in the querystrings and has no reliance on .'s in the url

function getPageName() {
    //#### Grab the url
    var FullUrl = window.location.href;

    //#### Remove QueryStrings
    var UrlSegments = FullUrl.split("?")
    FullUrl = UrlSegments[0];

    //#### Extract the filename
    return FullUrl.substr(FullUrl.lastIndexOf("/") + 1);
}
Cockerham answered 23/9, 2015 at 10:6 Comment(1)
True, but the importance of query solutions is questionable because it is not mentioned in the question. It is a choise between using '/' in query if any query at all or having shorter code.Gumma
W
0

Try this

url.substring(url.lastIndexOf('/')+1, url.length)
Weaponeer answered 18/1, 2016 at 9:52 Comment(1)
Works if you change url.length. See my answer.Gumma
G
0
function getFileNameWithoutExtension(url) {
  if (typeof url !== 'string') throw new Error('url must be a string');
  // Remove the QueryString
  return url.replace(/\?.*$/, '')
  // Extract the filename
  .split('/').pop()
  // Remove the extension
  .replace(/\.[^.]+$/, '');
}

This will return news from this URL http://www.myblog.com/news.php?year=2019#06.

Goodbye answered 16/2, 2016 at 22:3 Comment(3)
Doesn't split on '.' to remove the extension as asked forGumma
@PauliSudarshanTerho you are right, it seems I did not read the question well, I corrected my answer. My code is less performant than the accepted answer, however it works with filenames like "news.inc.php" and it is easier to read.Goodbye
The accepted answer is not correct at all: Miss a lot of points.. does not check if url is undefined ... does not split on '.' ... does not remove eventual query string .... It is my comment thereGumma
G
0
url? url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.')):''
  • Safety is as asked for. when url is null or undefined the result is ''.
  • Removes all of the path with ':', dots and any symbol including the last '/'.
  • This gives the true answer 'th' as asked and not 'th.index'. That is very important of course to have it work at all.
  • It allows filename to have several periods!

  • Not asked, but you can also have a query string without '/' and '.'

It is a corrected answer from Abhishek Sharma so I gave him an upvote. So genious and minimal one-liner - I saw it there :)

Gumma answered 16/6, 2019 at 21:4 Comment(4)
See my last point: Not asked, but you can also have a query string without '/' and '.' so that url has '/' in the query.Gumma
Between last '/' and last '.' is an empty name and I checked that gave it correctly ignoring the .vimrc extension.Gumma
It gives %E6%96%87%E4%BB%B6%E5%90%8D, shouldn't it?Gumma
I pasted the symbols into http://example.com/文件名.html and the alert() say 文件名Gumma
S
0

ES6 syntax based on TypeScript

Actually, the marked answer is true but if the second if doesn't satisfy the function returns undefined, I prefer to write it like below:

const getFileNameFromUrl = (url: string): string => {
  if (url) {
    const tmp = url.split('/');
    const tmpLength = tmp.length;

    return tmpLength ? tmp[tmpLength - 1] : '';
  }

  return '';
};

For my problem, I need to have the file extension.

Score answered 25/8, 2020 at 8:19 Comment(2)
If someone doesn't need the file extension then can use split('.') on returned string and join all elements without last entry of array.Dever
@ArkadiuszWieczorek, Exactly you right, thanks for your hint. 🌹Score
N
0

Simple Function (Using RegEx Pattern)

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}

var sample='/folder/another/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "/folder/another/",
  "file": "file.min.js",
  "name": "file.min",
  "ext": ".js"
}
*/
console.log(result.name);
Nolly answered 9/2, 2022 at 17:38 Comment(0)
K
0

Using RegEx

Let´s say you have this url:

http://127.0.0.1:3000/pages/blog/posts/1660345251.html

Using the following line of code:

var filename = location.pathname.replace(/[\D]/g, "");

Will return:

1660345251
  • Notice that this number is Unix Time, which returns your local time no matter where you are in the World (this should give you really unique post names for this blog example).
  • .replace(/[\D]/g, ""), replaces any non-digit character with an empty string. /[\D]/g says non-digit, and "" says empty string. More about it: here for numbers and here for letters.
  • More about RegEx, here. There are lots of RegEx tools out there that can help you out to get better results in the returning value for filename.

Extra code: Unix Time to Local Time

var humanDate = new Date(0);
var timestamp = entries[index].timestamp;
humanDate.setUTCSeconds(timestamp);

humanDate is for my local time:

Fri Aug 12 2022 20:00:51 GMT-0300 (Argentina Standard Time)

Credits for this code, here.

Kennethkennett answered 13/8, 2022 at 1:35 Comment(0)
V
0
function getFilenameFromUrlString(url) {
 const response = {
   data: {
     filename: ""
   },
   error: ""
 };
 try {
   response.data.filename = new URL(url).pathname.split("/").pop();
 } catch (e) {
   response.error = e.toString();
 }
 return response;
}

For tests check this: https://codesandbox.io/s/get-filename-from-url-string-wqthx1

Verla answered 12/10, 2022 at 3:25 Comment(0)
C
0

if any lazy person just wants the file name without extension,here it is

const url='https://test.s3.us-west-2.amazonaws.com/d.pdf';
const filename = url.split('/').pop().split('.')[0] //187392504
Cicatrize answered 19/10, 2023 at 6:7 Comment(0)
H
0

Other way to convert to URL first:

function getFilenameFromUrl(url: string): string | null {
    try {
        const parsedUrl = new URL(url);
        const pathname = parsedUrl.pathname;
        const pathComponents = pathname.split('/');
        const filename = pathComponents[pathComponents.length - 1]; // Get the last component (filename)
        return filename;
    } catch (error) {
        console.error('Error parsing URL:', error);
        return null;
    }
}

// Example usage:
const url = "https://example.com/api/alerting/image/f1635b2b-7946-422a-85c1-aaf52f0e944a/1f5f648d-cc0d-4c95-b06f-eb28b770156d8436546758293928039.zip";
const filename = getFilenameFromUrl(url);

if (filename) {
    console.log('Filename extracted:', filename);
} else {
    console.log('Failed to extract filename from URL');
}
Hillary answered 10/4 at 23:44 Comment(0)
S
-1

from How to get the file name from a full path using JavaScript?

var filename = fullPath.replace(/^.*[\\\/]/, '')
Salomone answered 15/7, 2016 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.