I am using the Flex SDK and able to capitalise the first letter of every word as follows:
textInput.text.toLowerCase().replace(/\b./g,function(...m):String{return m[0].toUpperCase()})
This works fine, however letters after punctuation are also being capitalised, which works in some cases (e.g. O'Neil) but not others (e.g. Connah'S Quay).
I want to have the code only look at letters at the start of a string and letters after a space. Can anyone provide the correct code to use in this instance please?
This snippet might help:
function firstLetterUpperCase(strData:String):String
{
var strArray:Array = strData.split(' ');
var newArray:Array = [];
for (var str:String in strArray)
{
newArray.push(strArray[str].charAt(0).toUpperCase() + strArray[str].slice(1));
}
return newArray.join(' ');
}
//testing
var strs = "Testing cases (e.g. o'Neil) and others (e.g. connah's quay)."
trace(firstLetterUpperCase(strs));
Result is:
//Testing Cases (e.g. O'Neil) And Others (e.g. Connah's Quay).
If you prefer, try this regex:
/(^| )./g
var input = "i aM tHe kiNG";
capitalised = capitalize(input);
function capitalize(input)
{
var splited = input.split(" ");
//console.log(splited);
var output = Array();
for (i in splited)
{
//convert each letter into lower case
var temp = splited[i].toLowerCase();
//Convert the first char upper case and join with the rest letters of word.
temp = temp.charAt(0).toUpperCase() + temp.substring(1);
//store the word in the array
output.push(temp);
}
//join the words
return output.join(" ");
}
The output will be: I Am The King
private function capitalise(s:String):String
{
var strArray:Array = s.split(' ');
var newArray:Array = new Array();
for each (var str:String in strArray)
newArray.push(str.charAt(0).toUpperCase()+str.slice(1));
return newArray.join(' ');
}
trace(capitalise("this is a test - o'Neil - connah's quay"));
// Output: This Is A Test - O'Neil - Connah's Quay
var test = "thIS is a test ansWER to stack OVERFlow";
function process(sentence) {
var words = sentence.split(" ");
var processed = '';
for(var i=0; i < words.length; i++) {
processed += words[i].substr(0,1).toUpperCase() +
words[i].substr(1).toLowerCase();
if(i < words.length-1) {
processed += " ";
}
}
return processed;
}
console.log(process(test));