Capitalize first letter of every word in Lua

iRyanBell picture iRyanBell · Nov 29, 2013 · Viewed 8.5k times · Source

I'm able to capitalize the first letter of my string using:

str:gsub("^%l", string.upper)

How can I modify this to capitalize the first letter of every word in the string?

Answer

n1xx1 picture n1xx1 · Nov 29, 2013

I wasn't able to find any fancy way to do it.

str = "here you have a long list of words"
str = str:gsub("(%l)(%w*)", function(a,b) return string.upper(a)..b end)
print(str)

This code output is Here You Have A Long List Of Words. %w* could be changed to %w+ to not replace words of one letter.


Fancier solution:

str = string.gsub(" "..str, "%W%l", string.upper):sub(2)

It's impossible to make a real single-regex replace because lua's pattern system is simple.