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( "taptest" )
local rmsuffix = require( "rmsuffix" )

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

t()

See also