Skip to content

Str

Source: shiva-fw/libs/str/init.lua

String utility library.

Availability

Str is a global in every shiva module (loaded by sh_init.lua). No import required.

Trimming

lua
Str.trim(s)    -- remove leading and trailing whitespace
Str.ltrim(s)   -- left trim only
Str.rtrim(s)   -- right trim only

Case Conversion

lua
Str.ucfirst(s)  -- 'hello' → 'Hello'
Str.lcfirst(s)  -- 'Hello' → 'hello'
Str.title(s)    -- 'hello world' → 'Hello World'
Str.snake(s)    -- 'helloWorld' → 'hello_world'
Str.camel(s)    -- 'hello_world' → 'helloWorld'
Str.pascal(s)   -- 'hello_world' → 'HelloWorld'
Str.kebab(s)    -- 'helloWorld' → 'hello-world'

Testing

lua
Str.startsWith(s, prefix)  -- boolean
Str.endsWith(s, suffix)    -- boolean
Str.contains(s, sub)       -- boolean
Str.isEmpty(s)             -- true if nil or ''
Str.isNotEmpty(s)          -- true if not nil and not ''

Splitting and Joining

Str.split(s, delimiter)

Split a string by delimiter. Returns a string[].

lua
Str.split('a,b,c', ',')  -- { 'a', 'b', 'c' }

Truncation and Padding

Str.truncate(s, maxLen, suffix?)

Truncate to maxLen characters. Default suffix: '...'.

lua
Str.truncate('Hello World', 8)  -- 'Hello...'

Str.padLeft(s, len, char?)

Pad the left side to reach len. Default char: ' '.

lua
Str.padLeft('5', 3, '0')   -- '005'

Str.padRight(s, len, char?)

Pad the right side to reach len.

lua
Str.padRight('hi', 5)   -- 'hi   '

Replacement

Str.replaceFirst(s, find, replace)

Replace the first occurrence of find (literal, not a pattern).

lua
Str.replaceFirst('aaa', 'a', 'b')  -- 'baa'

Str.replace(s, find, replace)

Replace all occurrences (literal).

lua
Str.replace('a.b.c', '.', '-')  -- 'a-b-c'

Generation

Str.random(length, charset?)

Generate a random string. Default charset: alphanumeric.

lua
Str.random(16)
Str.random(8, '0123456789')  -- numeric only

Str.slug(s)

Convert to a URL-safe slug.

lua
Str.slug('Hello World!')  -- 'hello-world'

Released under the MIT License.