js function to get filename from url

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

    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.

提交回复
热议问题