I want to know if there is something like string.lower or string.upper but only makes the first letter uppercase, if not, how do i make something like that?
Just get the first letter of the character and make that uppercase.
local Text = "hello there"
local FirstLetter = string.sub(Text, 1, 1)
FirstLetter = FirstLetter:upper() -- Or :lower() depending on what you want to do
Text = FirstLetter..string.sub(Text, 2, -1)
There is no pre-made function for it. You just have to hard-code it in. You could also put it in one line like this:
(string.sub(String, 1, 1)):upper()..string.sub(String, 2, -1)
Although at that point, you might just want to make a function called firstUpper()
or something. Hope this helped.
2 Likes
Found this on stackoverflow. Search before coming here, please.
function firstToUpper(str)
return (str:gsub("^%l", string.upper))
end
It’s also shorter compared to @Batimius’ method.
13 Likes
That works, though in other languages it also makes the other letters lowercase, so what you could do is lowercase it before uppercasing the first letter
function firstToUpper(str)
return (str:lower():gsub("^%l", string.upper))
end
print(firstToUpper("HELLO")) --Prints Hello
--OG Method would return the same string because it wouldn't lowercase
5 Likes
Thank you for your solution
I even went further and improve it slightly for my case but maybe other will find it useful
local firstUpperExpression = "%^([ -]*%l)"
-- this will deal with situations where i have " " or "-" in front
function firstToUpper(str)
return (str:lower():gsub(firstUpperExpression , string.upper))
end
print(firstToUpper(" - HELLO")) --Prints: - Hello
print(firstToUpper("HeLLO")) --Prints: Hello
1 Like