extname

function extname( path ) --> ext

Description

Returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path.

Parameters

path

Path with file name.

Return Values

ext

File name extension.

Code

--ZFUNC-extname-v1
local function extname( path ) --> ext
   local i = #path
   local c = string.sub( path, i, i )
   while i > 0 and c ~= "." do
      i = i - 1
      c = string.sub( path, i, i )
      if c == "/" then return "" end
   end

   if i == 0 then return "" end -- empty path

   return string.sub( path, i )
end

return extname

Examples

local t = require( "taptest" )
local extname = require( "extname" )

t( extname( "index.html" ), ".html" )
t( extname( "index.coffee.md" ), ".md" )

t( extname( "index.." ), "." )
t( extname( "index" ), "" )

t( extname( ".index" ), ".index" )
t( extname( "/.index" ), ".index" )

t( extname( "abc.def/index" ), "" )

t()