是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。


当前回答

约翰·史密斯->约翰·史密斯

'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );

其他回答

这是基于我对FreeCodeCamp的Bonfire“Title Case”的解决方案,它要求你首先将给定的字符串转换为所有小写,然后将每个字符进行空格转换为大写。

不使用regex:

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}

只是另一个版本的混合。这也将检查字符串是否。长度为0:

String.prototype.toTitleCase = function() {
    var str = this;
    if(!str.length) {
        return "";
    }
    str = str.split(" ");
    for(var i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
    }
    return (str.length ? str.join(" ") : str);
};

如果一个CSS解决方案满足你的需求,你可以应用文本转换CSS样式到你的控件:

text-transform: capitalize;

请注意,这将会改变: hello world到hello world HELLO WORLD到HELLO WORLD(不变) emily-jane o'brien致emily-jane o'brien(不正确) 玛丽亚·冯·特拉普写给玛丽亚·冯·特拉普(不正确)

一种稍微优雅一点的方式,改编了Greg Dean的功能:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

这样称呼它:

"pascal".toProperCase();

没有正则表达式,没有循环,没有分割,没有子字符串:

String.prototype.toTitleCase = function(){返回this.valueOf().toLowerCase().replace(this.valueOf()[0], this.valueOf()[0].toUpperCase());} console.log(“莱拉”.toTitleCase ());