Javascript regex for matching/extracting file extension

后端 未结 4 1542
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 13:21

The following regex

var patt1=/[0-9a-z]+$/i;

extracts the file extension of strings such as

filename-jpg
filename#gif
fil         


        
4条回答
  •  臣服心动
    2020-12-02 14:02

    Try

    var patt1 = /\.([0-9a-z]+)(?:[\?#]|$)/i;
    

    This RegExp is useful for extracting file extensions from URLs - even ones that have ?foo=1 query strings and #hash endings.

    It will also provide you with the extension as $1.

    var m1 = ("filename-jpg").match(patt1);
    alert(m1);  // null
    
    var m2 = ("filename#gif").match(patt1);
    alert(m2);  // null
    
    var m3 = ("filename.png").match(patt1);
    alert(m3);  // [".png", "png"]
    
    var m4 = ("filename.txt?foo=1").match(patt1);
    alert(m4);  // [".txt?", "txt"]
    
    var m5 = ("filename.html#hash").match(patt1);
    alert(m5);  // [".html#", "html"]
    

    P.S. +1 for @stema who offers pretty good advice on some of the RegExp syntax basics involved.

提交回复
热议问题