How do I cut off a string at a certain character?

Basically, if I have a string that has 2 parts separated by an underscore, I’d want to only get the first part.

For example, if I have a string that says “hello_world” then I’d want it to print “hello” instead of “hello_world”. I’ve heard of split() but I have no idea how it works, even after reading a bunch of forum posts.

How would I do this?

1 Like
local str = "hello_world" -- the original string
local split = string.split(str, "_") -- this separates the string by the "_" character and turns it into an arraY
-- split: {"hello", "world"}
local hello = split[1] -- get the first element from the table

print(hello) --> prints "hello"
1 Like

You can use substring and find() to get the index of the underscore

local string = "Hello_world!"-- the string to cut the end off
local cutString = string.sub(string,1, string.find(string,"_")-1)
print(cutString) -- outputs "Hello"
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.