Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I capitalize the first letter of every word of a given string value?

Asked by 5 years ago
Edited 5 years ago

Example: "the quick brown fox jumps over the lazy dog " to "The Quick Brown Fox Jumps Over The Lazy Dog"

1 answer

Log in to vote
1
Answered by
Amiaa16 3227 Moderation Voter Community Moderator
5 years ago

Split it by space, grab the first letter of every word, upper it and then put everything back together.

local str = "a quick brown fox blabla"
local spl = string.split(str, " ") --split by space
for i,word in pairs(spl) do
    local firstLetter = word:sub(1,1) --get the 1st letter of the word
    local theRest = word:sub(2) --grt everything except the first letter
    spl[i] = firstLetter:upper() .. theRest
end

local result = table.concat(spl, " ") --put it back together
print(result)

A shorter version:

local str = "a quick brown fox blabla"
local spl = string.split(str, " ")
for i,v in pairs(spl) do
    spl[i] = v:sub(1,1):upper() .. v:sub(2)
end
local result = table.concat(spl, " ")
Ad

Answer this question