admin管理员组

文章数量:1129022

I have a url like .html

I need a javascript function to give me the 'th' value from that.

All my urls have the same format (2 letter filenames, with .html extension).

I want it to be a safe function, so if someone passes in an empty url it doesn't break.

I know how to check for length, but I should be checking for null to right?

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 letter filenames, with .html extension).

I want it to be a safe function, so if someone passes in an empty url it doesn't break.

I know how to check for length, but I should be checking for null to right?

Share Improve this question asked Feb 4, 2009 at 15:11 BlankmanBlankman 267k330 gold badges795 silver badges1.2k bronze badges 2
  • 1 Possible duplicate of How to get the file name from a full path using JavaScript? – Liam Commented Aug 2, 2017 at 13:45
  • For something as specific as you want, you may use RegEx: stackoverflow.com/a/73341035/7389293 – carloswm85 Commented Aug 13, 2022 at 1:36
Add a comment  | 

26 Answers 26

Reset to default 233
var filename = url.split('/').pop()

Why so difficult?

= url.split('#')[0].split('?')[0].split('/').pop();

RegEx below would result same as the above's normally, but will return empty string if the URL was significantly malformed.

= (url.match(/^\w+:(\/+([^\/#?\s]+)){2,}(#|\?|$)/)||[])[2]||'';
// Returns empty string for relative URLs unlike the original approach

= (url.match(/^\w+:(\/+([^\/#?\s]+)){2,}/)||[])[2]||'';
// Ignores trailing slash (e.g., ".../posts/?a#b" results "posts")

All three of them would return file

本文标签: javascriptjs function to get filename from urlStack Overflow