How would I capitalize first letter in a string?

I am making an admin system for fun and I want to convert the first letter of this string to a capital letter:

"test" and convert it to "Test"

I have seen people use string.gsub and string.upper. I already know how string.upper works but I am not to sure of how string.gsub works. Can someone give me and example?

2 Likes

There may be a simpler/better way of doing it that someone else could suggest but this works:

local str="test"
str=(string.upper(string.sub(str, 1, 1))..string.sub(str, 2, -1)) 
print(str) -- output:  Test  -  Server - Script:3
3 Likes

Hello thanks for the reply. I have used your code and yes it does work and yes there may be a better way. But I am wondering if you could explain how the code work as I still to understand what the code does.

string.sub(string, startpoint, endpoint)
string.upper(string.sub(str, 1, 1)) - Takes the first letter of the string and makes it upper case.
…string.sub(str, 2, -1) this just copies the rest of the string (from position 2 to the end) and adds it at the end of the captialized letter.
You can find out more about string manipulation here:
https://developer.roblox.com/en-us/api-reference/lua-docs/string

6 Likes

Just to clarify, so string.sub() takes the string as its first argument which is ‘test’, the starting point of the string so the letter t for test, and the endpoint meaning the last letter of the word test?

the last argument is the number of characters to take, so 1, 1 would start at position 1 and only take 1 character, if you use -1 for the last argument it will take all characters from the position specified to the end of the string.
string.sub(str, 1, 1) - Starts at character 1 and takes 1 character
string.sub(str, 2, -1) - Takes whole string starting from character 2
string.sub(str, 2, 3) - would take 3 characters starting from character 2 so if you used the word script as an example it would return cri

local s = "hello world!"
s = string.gsub(s, "^%l", function(c) return string.upper(c) end)
print(s) --Hello world!
7 Likes