js function to get filename from url

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

    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)

提交回复
热议问题