js function to get filename from url

前端 未结 19 2628
挽巷
挽巷 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: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 :)

提交回复
热议问题