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( "tapered" )
local extname = require( "extname" )

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

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

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

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

t.done()