Make a string Proper Case with gsub?

Hello, I’d like to a function in my script that converts any given string to Proper Case, capitalising the first letter of each word using gsub

For example:

local str == "random string here"

print(properCase(str)) -- expected result: "Random String Here"

Anyone got ideas? I’ve looked and can’t find a satisfactory answer.

Thanks! :slight_smile:

1 Like

There might be an easier way but I would use split and sub, not gsub:

local function toProper(string)
    local split = string:split(' ')
    for i,v in ipairs(split) do
        split[i] = v:sub(1, 1):upper()..v:sub(2):lower()
    end
    return table.concat(split, ' ')
end
1 Like
local function convertToTitle(s)
	s = s:gsub("^(.)", function(c) return c:upper() end)
	s = s:gsub("(%s.)", function(c) return c:upper() end)
	return s
end

print(convertToTitle("random string here")) --Random String Here

Unfortunately Lua string patterns don’t allow for logic operators in the same way Regex does so I wasn’t able to write a single-liner.

1 Like