如何将字符串中每个单词的第一个字母大写 [英] How to capitalise the first letter of every word in a string
本文介绍了如何将字符串中每个单词的第一个字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Flex SDK,并且能够将每个单词的首字母大写,如下所示:
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()})
这很好用,但是标点符号后面的字母也大写,这在某些情况下有效(例如 O'Neil),但在其他情况下无效(例如 Connah'S Quay).
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?
推荐答案
这个片段可能有帮助:
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).
这篇关于如何将字符串中每个单词的第一个字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文