Javascript regex for matching/extracting file extension

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)