String manipulation

What’s the most effective way to ‘cut off’ the last word in a string?

For example:

"Standard Car Red"


"Standard Car"
1 Like

If you define a “word” as a string of non-space characters then %S+ will match it, and the $ anchor will ensure it is at the end of the string.

local s = ("Standard Car Red"):gsub("%S+$", "")

The result will be "Standard Car "; if you want to get rid of the extra space(s) before the last word then include %s* in the pattern: %s*%S+$

If a “word” is only a string of alphanumeric characters then %w+ will match it, and (%W*) will capture the rest of the string after it, like punctuation, and %1 in gsub’s replace argument will reference the captured string.

local s = ("Standard Car Red.-=[];,/"):gsub("%s*%w+(%W*)$", "%1")

results in "Standard Car.-=[];,/"


That’s great, thank you.

What’s the best way to go about learning this? I know Roblox have a page on string manipulation but I can’t find anything on ‘%S+’, '$", etc

1 Like

The DevHub search doesn’t work very well; not surprised you couldn’t find it.


Perfect, thanks!

The lua 5.1 manual describes the pattern matching language
“Programming in Lua” also has sections on patterns and captures