js function to get filename from url

前端 未结 19 2588
挽巷
挽巷 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条回答
  •  Happy的楠姐
    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')
      })
    })
    

提交回复
热议问题