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


当前回答

一种方法使用减少

函数titleCase(str) { Const arr = str.split(" "); Const result = arr。Reduce ((acc, cur) => { const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase(); 返回${newStr} }, " ") 返回的结果。片(0,result.length-1); }

其他回答

一种方法使用减少

函数titleCase(str) { Const arr = str.split(" "); Const result = arr。Reduce ((acc, cur) => { const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase(); 返回${newStr} }, " ") 返回的结果。片(0,result.length-1); }

只是另一个版本的混合。这也将检查字符串是否。长度为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);
};

你可以立即toLowerCase字符串,然后只是toUpperCase每个单词的第一个字母。变成了非常简单的一行:

函数titleCase(str) { 返回str.toLowerCase()。/\b\w/g, s => s. touppercase ()); } console.log (titleCase(‘钢铁侠’); console.log (titleCase(“绿巨人”);

试试这个:

function toTitleCase(str) str归来。replace ( - w \ S * / g, 功能(. txt) { 归来txt.charAt(0). toupfaith (+ txt.substr) 的 ); 的 < form > 输入: <br /><textarea" > < / textarea > < br / >输出: <br /><textarea" > < / textarea > < / form >

如果你可以在你的代码中使用第三方库,那么lodash为我们提供了一个帮助函数。

https://lodash.com/docs/4.17.3#startCase

_。startCase (foo栏); // => 'Foo Bar' _.startCase(“——foo bar”); // => 'Foo Bar' _.startCase(“fooBar”); // => 'Foo Bar' _.startCase(“__FOO_BAR__”); // => ' foo bar '