rmsuffix

function rmsuffix( str, suffix ) --> nstr

Description

If str ends with suffix returns the function a new string without the suffix, otherwise str itself.

Parameters

str

The string that should lose the suffix.

suffix

The suffix that should be removed.

Return Values

nstr

A new string without the suffix.

Code

--ZFUNC-rmsuffix-v1
local function rmsuffix( str, suffix ) --> nstr
   local suffixlen = string.len( suffix )
   local endsub = string.sub( str, -suffixlen )
   if endsub == suffix then
      local n = string.len( str ) - suffixlen
      return string.sub( str, 1, n )
   else
      return str
   end
end

return rmsuffix

Examples

local t = require( "tapered" )
local rmsuffix = require( "rmsuffix" )

t.is( "node", rmsuffix( "node.txt", ".txt" ) )
t.is( "node.txt", rmsuffix( "node.txt", ".adoc" ) )
t.is( "node.txt", rmsuffix( "node.txt.txt", ".txt" ) )

t.done()

See also