More actions
created |
No edit summary |
||
Line 1: | Line 1: | ||
local | local StringEx = {} | ||
function | function StringEx:contains(sub) | ||
return self:find(sub, 1, true) ~= nil | return self:find(sub, 1, true) ~= nil | ||
end | end | ||
function | function StringEx:startswith(start) | ||
return self:sub(1, #start) == start | return self:sub(1, #start) == start | ||
end | end | ||
function | function StringEx:endswith(ending) | ||
return ending == "" or self:sub(-#ending) == ending | return ending == "" or self:sub(-#ending) == ending | ||
end | end | ||
function | function StringEx:replace(old, new) | ||
local s = self | local s = self | ||
local search_start_idx = 1 | local search_start_idx = 1 | ||
Line 32: | Line 32: | ||
end | end | ||
function | function StringEx:insert(pos, text) | ||
return self:sub(1, pos - 1) .. text .. self:sub(pos) | return self:sub(1, pos - 1) .. text .. self:sub(pos) | ||
end | end | ||
return | return StringEx |
Latest revision as of 07:15, 30 May 2025
Adapted from https://gist.github.com/kgriffs/124aae3ac80eefe57199451b823c24ec
local StringEx = {}
function StringEx:contains(sub)
return self:find(sub, 1, true) ~= nil
end
function StringEx:startswith(start)
return self:sub(1, #start) == start
end
function StringEx:endswith(ending)
return ending == "" or self:sub(-#ending) == ending
end
function StringEx:replace(old, new)
local s = self
local search_start_idx = 1
while true do
local start_idx, end_idx = s:find(old, search_start_idx, true)
if (not start_idx) then
break
end
local postfix = s:sub(end_idx + 1)
s = s:sub(1, (start_idx - 1)) .. new .. postfix
search_start_idx = -1 * postfix:len()
end
return s
end
function StringEx:insert(pos, text)
return self:sub(1, pos - 1) .. text .. self:sub(pos)
end
return StringEx