我正在使用Flex SDK并能够将每个单词的首字母大写如下:
textInput.text.toLowerCase().replace(/\b./g,function(...m):String{return m[0].toUpperCase()})
这样可以正常工作,但标点后的字母也被大写,在某些情况下(例如O'Neil)有效,但在其他情况下无效(例如Connah'S Quay)。
我希望代码只查看字符串开头的字母和空格后的字母。任何人都可以在这个例子中提供正确的代码吗?
答案 0 :(得分:4)
此代码段可能有所帮助:
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));
结果是:
//Testing Cases (e.g. O'Neil) And Others (e.g. Connah's Quay).
答案 1 :(得分:1)
如果您愿意,请尝试使用此正则表达式:
/(^| )./g
答案 2 :(得分:0)
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(" ");
}
输出将是:我是国王
答案 3 :(得分:0)
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
答案 4 :(得分:0)
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));