Javascript regex for matching/extracting file extension

后端 未结 4 1528
爱一瞬间的悲伤
爱一瞬间的悲伤 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:05

    Example list:

    var fileExtensionPattern = /\.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$/gmi
    //regex flags -- Global, Multiline, Insensitive
    
    var ma1 = 'css/global.css?v=1.2'.match(fileExtensionPattern)[0];
    console.log(ma1);
    // returns .css
    
    var ma2 = 'index.html?a=param'.match(fileExtensionPattern)[0];
    console.log(ma2);
    // returns .html
    
    var ma3 = 'default.aspx?'.match(fileExtensionPattern)[0];
    console.log(ma3);
    // returns .aspx
    
    var ma4 = 'pages.jsp#firstTab'.match(fileExtensionPattern)[0];
    console.log(ma4);
    // returns .jsp
    
    var ma5 = 'jquery.min.js'.match(fileExtensionPattern)[0];
    console.log(ma5);
    // returns .js
    
    var ma6 = 'file.123'.match(fileExtensionPattern)[0];
    console.log(ma6);
    // returns .123
    

    Test page.

提交回复
热议问题