Skip to content

Instantly share code, notes, and snippets.

@jacksonie
Forked from kgriffs/string_util.lua
Created November 3, 2024 00:04
Show Gist options
  • Save jacksonie/acf39bf5093e54ee4cbd879f31fffe33 to your computer and use it in GitHub Desktop.
Save jacksonie/acf39bf5093e54ee4cbd879f31fffe33 to your computer and use it in GitHub Desktop.

Revisions

  1. @kgriffs kgriffs created this gist May 27, 2020.
    35 changes: 35 additions & 0 deletions string_util.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@

    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