util.string.sub
Shared
Extracts a substring from a string
Syntax
local result = util.string.sub(
input,
start_at,
end_at = -1
)Parameters
| Type | Name | Description |
|---|---|---|
string | input | String to extract from |
int | start_at | Character position where extraction begins - negative counts from end |
int | end_at | Character position where extraction ends - negative counts from end |
Returns
| Type | Name | Description |
|---|---|---|
string | result | Extracted substring within string's specified range |
Examples
local result = util.string.sub("hello world", 1, 5)
core.engine.print("info", result) -- 'hello'local result = util.string.sub("hello world", 7)
core.engine.print("info", result) -- 'world'local result = util.string.sub("hello", -3)
core.engine.print("info", result) -- 'llo'local result = util.string.sub("hello world", 1, -7)
core.engine.print("info", result) -- 'hello'local result = util.string.sub("hello world", 2, -2)
core.engine.print("info", result) -- 'ello worl'local char = util.string.sub("hello", 1, 1)
core.engine.print("info", char) -- 'h'local last = util.string.sub("hello", -1)
core.engine.print("info", last) -- 'o'local filename = "document.txt"
local ext = util.string.sub(filename, -3)
core.engine.print("info", ext) -- 'txt'local text = "hello world"
local space = util.string.find(text, " ")
local firstWord = util.string.sub(text, 1, space - 1)
core.engine.print("info", firstWord) -- 'hello'local str = "[hello]"
local inner = util.string.sub(str, 2, -2)
core.engine.print("info", inner) -- 'hello'local str = "hello"
local copy = util.string.sub(str, 1, -1)
core.engine.print("info", copy) -- 'hello'local result = util.string.sub("hello", 5, 3)
core.engine.print("info", result) -- ''local result = util.string.sub("hello", 1, 100)
core.engine.print("info", result) -- 'hello'local result = util.string.sub("hello", -5, -1)
core.engine.print("info", result) -- 'hello'local date = "2024-01-15"
local year = util.string.sub(date, 1, 4)
core.engine.print("info", year) -- '2024'local date = "2024-01-15"
local month = util.string.sub(date, 6, 7)
core.engine.print("info", month) -- '01'local str = "abcdefgh"
for i = 1, #str, 2 do
local chunk = util.string.sub(str, i, i + 1)
core.engine.print("info", chunk)
end
--[[
Output:
'ab'
'cd'
'ef'
'gh'
]]local long = "This is a very long string"
local short = util.string.sub(long, 1, 10).."..."
core.engine.print("info", short) -- 'This is a ...'local str = "hello world"
if util.string.sub(str, 1, 5) == "hello" then
core.engine.print("info", "Starts with hello")
endlocal str = "prefix_content_suffix"
local content = util.string.sub(str, 8, 14)
core.engine.print("info", content) -- 'content'