在字符串中大写单词的最佳方法是什么?
当前回答
只要输入字符串中没有重音字母,vsync提供的答案就可以工作。
我不知道原因,但显然\b在regexp匹配也重音字母(在IE8和Chrome上测试),所以像“località”这样的字符串会被错误地大写转换为“LocalitÀ”(à字母被大写,因为regexp认为这是一个单词边界)
一个更通用的函数也适用于重音字母是这样的:
String.prototype.toCapitalize = function()
{
return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}
你可以这样使用它:
alert( "hello località".toCapitalize() );
其他回答
John Resig (jQuery的成名者)将John Gruber编写的perl脚本移植到JavaScript。这个脚本以一种更聪明的方式大写,它没有大写像“of”和“and”这样的小词。
你可以在这里找到它:Title资本化JavaScript
这段代码将点后的单词大写:
function capitalizeAfterPeriod(input) {
var text = '';
var str = $(input).val();
text = convert(str.toLowerCase().split('. ')).join('. ');
var textoFormatado = convert(text.split('.')).join('.');
$(input).val(textoFormatado);
}
function convert(str) {
for(var i = 0; i < str.length; i++){
str[i] = str[i].split('');
if (str[i][0] !== undefined) {
str[i][0] = str[i][0].toUpperCase();
}
str[i] = str[i].join('');
}
return str;
}
我将使用regex来实现这个目的:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
function capitalize(s){
return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
输出:“这是有史以来最糟糕的字符串”
更新:
这个解决方案似乎取代了我的:https://stackoverflow.com/a/7592235/104380
既然每个人都给了您所要求的JavaScript答案,我将添加CSS属性text-transform: capitalize将执行此操作。
我意识到这可能不是你想要的-你没有给我们任何上下文,你正在运行这个-但如果它只是为了表示,我肯定会选择CSS替代方案。