Alternative method using regex.
Code: Select all
string = "Today is a beautiful day.";
find = findAll(string, "(\\w)(\\w*\\W*)", true);
output = "";
for(i in find)
output = output + toUpperCase(i[1]) + i[2];
Regex syntax explanation
\\w = match the first letter of the word (abc...xyz, 0-9)
\\w* = match the rest of the letter of the word, in case of only single char word, this is blank
\\W* = match any non word (capital letter W), this include space, symbol, tab, etc
The brackets are to capture the groups, we have 2, :1st for the first letter, and 2nd for the rest and the separator
The advantage of this is it can detect double/multi spaces and non space char, example tab ("\t"). So even if
string = "Today//is a beautiful:day."
It still can properly uppercase only the words, keep all the fancy non space char intact.
output = "Today//Is A Beautiful:Day."
====================
@Martin : how does the replaceAll() replace the matched group ($1 $2 $3, ....)? I am trying to solve this usage case, using only replaceAll(), with this script. It supposed to be 2 lines script only
Code: Select all
string = "Today is a beautiful day.";
output = replaceAll(string, "(\\w)(\\w*\\W*)", toUpperCase("$1") + "$2");
//output = Today is a beautiful day.
But after several testing, it never convert the first letter to uppercase. I try to add "a" char before the $1, the "a" is converted properly.
Code: Select all
output = replaceAll(string, "(\\w)(\\w*\\W*)", toUpperCase("a$1") + "$2");
//output = AToday Ais Aa Abeautiful Aday.
After more testing, I realized that $1 is always replaced only after all other function evaluated. That's why
toUpperCase("$1") is always evaluated to "$1" in each iteration,
not
toUpperCase("T") >> first iteration, toUpperCase("i") >> second iteration, ....
I read the explanation from javascript replaceAll() :
https://stackoverflow.com/questions/614 ... javascript
The solution is to use function to overcome the replacement. But of course Automagic doesn't have function yet.
I tried something similar, by assigning the $1 to x first (I expect the $1 is replace by the captured group first), but still the $1 always only replaced at the end, after everything evaluated. Tried with eval() also give same $1 result.
Code: Select all
string = "Today is a beautiful day.";
x = 0;
output = replaceAll(string, "(\\w)(\\w*\\W*)", if(true) {x = "$1"; toUpperCase(x) + "$2" } );
//output = Today is a beautiful day.
//x = $1, I expect this to be T, i, a, b, d (should be "d" as the last iteration)