Search code examples
lualua-patterns

Capitalize first letter of every word in Lua


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?


Solution

  • 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.