REGEX: Capture Filename from URL without file extension

前端 未结 5 1288
忘掉有多难
忘掉有多难 2020-12-01 05:40

I am trying to create a Javascript Regex that captures the filename without the file extension. I have read the other posts here and \'goto this page: http://gunbl

5条回答
  •  伪装坚强ぢ
    2020-12-01 06:35

    var url = "http://example.com/index.htm";
    var filename = url.match(/([^\/]+)(?=\.\w+$)/)[0];
    

    Let's go through the regular expression:

    [^\/]+    # one or more character that isn't a slash
    (?=       # open a positive lookahead assertion
      \.      # a literal dot character
      \w+     # one or more word characters
      $       # end of string boundary
    )         # end of the lookahead
    

    This expression will collect all characters that aren't a slash that are immediately followed (thanks to the lookahead) by an extension and the end of the string -- or, in other words, everything after the last slash and until the extension.

    Alternately, you can do this without regular expressions altogether, by finding the position of the last / and the last . using lastIndexOf and getting a substring between those points:

    var url = "http://example.com/index.htm";
    var filename = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
    

提交回复
热议问题