js function to get filename from url

前端 未结 19 2626
挽巷
挽巷 2020-11-30 03:01

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

19条回答
  •  心在旅途
    2020-11-30 03:33

    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')

提交回复
热议问题