Javascript regex for matching/extracting file extension

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

    Just add a . to the regex

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

    Because the dot is a special character in regex you need to escape it to match it literally: \..

    Your pattern will now match any string that ends with a dot followed by at least one character from [0-9a-z].

    Example:

    [
      "foobar.a",
      "foobar.txt",
      "foobar.foobar1234"
    ].forEach( t => 
      console.log(
        t.match(/\.[0-9a-z]+$/i)[0]
      ) 
    )


    if you want to limit the extension to a certain amount of characters also, than you need to replace the +

    var patt1=/\.[0-9a-z]{1,5}$/i;
    

    would allow at least 1 and at most 5 characters after the dot.

提交回复
热议问题