js function to get filename from url

前端 未结 19 2493
挽巷
挽巷 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

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 03:36

    Try this

    url.substring(url.lastIndexOf('/')+1, url.length)
    
    0 讨论(0)
  • 2020-11-30 03:36
    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 :)

    0 讨论(0)
  • 2020-11-30 03:36
    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.

    0 讨论(0)
  • 2020-11-30 03:39

    Why so difficult?

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

    0 讨论(0)
  • 2020-11-30 03:39

    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')
      })
    })
    
    0 讨论(0)
提交回复
热议问题