Capitalize the first letter of each word in Lua

I can smooth the first letter of my string using:

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

How can I change this to make up the first letter of each word in a string?

+8
lua lua-patterns
source share
3 answers

I have not been able to find any fancy way to do this.

 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* can be changed to %w+ so as not to replace words with a single letter.


Fancier Solution:

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

It is not possible to make a real replacement for a single regex because the lua pattern system is simple.

+10
source share

in the alternative answer you will get conflicting results with words containing apostrophes:

str = string.gsub(" "..str, "%W%l", string.upper):sub(2) will make amends for the first letter after each apostrophe regardless if its first letter in the word

for example: "here is a long list of words" displays "Here is a long list of words"

to fix this i found a smart solution here

using this code:

 function titleCase( first, rest ) return first:upper()..rest:lower() end string.gsub(str, "(%a)([%w_']*)", titleCase) 

fix any problems caused by this strange error

0
source share
 function titleCase( first, rest ) return first:upper()..rest:lower() end string.gsub(str, "(%a)([%w_']*)", titleCase) BunchOfText {"Yeppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp"} 
0
source share

All Articles