-
-
Save 1715173329/5a82f98d059c4f3c5dd82b8708ce8e1f to your computer and use it in GitHub Desktop.
Lua string utilities (contains, startswith, endswith, replace, insert)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function string:contains(sub) | |
return self:find(sub, 1, true) ~= nil | |
end | |
function string:startswith(start) | |
return self:sub(1, #start) == start | |
end | |
function string:endswith(ending) | |
return ending == "" or self:sub(-#ending) == ending | |
end | |
function string: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 string:insert(pos, text) | |
return self:sub(1, pos - 1) .. text .. self:sub(pos) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment