js function to get filename from url

前端 未结 19 2617
挽巷
挽巷 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);
    }
    

提交回复
热议问题