Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
iRyanBell Avatar asked Nov 29 '13 11:11

iRyanBell


People also ask

How do you auto capitalize the first letter of every word?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.

How do you capitalize in Lua?

Converting a string to its uppercase in Lua is done by the string. upper() function.

How do you capitalize the first character of each word in a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.

How do I get the first letter of a capital in regex?

Example 2: Convert First letter to UpperCase using Regex The regex pattern is /^./ matches the first character of a string. The toUpperCase() method converts the string to uppercase.


2 Answers

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.

like image 163
n1xx1 Avatar answered Nov 07 '22 03:11

n1xx1


in the alternative answer listed you get inconsistent results with words containing apostrophes:

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

eg: "here's a long list of words" outputs "Here'S A Long List Of Words"

to fix this i found a clever solution here

utilizing this code:

function titleCase( first, rest )
   return first:upper()..rest:lower()
end

string.gsub(str, "(%a)([%w_']*)", titleCase)

will fix any issues caused by that weird bug

like image 44
Joe Avatar answered Nov 07 '22 05:11

Joe