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


当前回答

如果你可以在你的代码中使用第三方库,那么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 '

其他回答

可以将第一个字符大写,并与其余字符串连接。

Let STR = 'john smith'; Let res = str.split(" "); res.forEach((w, index) => { res[index] = w. charat (0). touppercase ().concat(w。片(1,w.length)) }); Res = Res .join(" "); console.log (res);

这是个测试——>这是个测试

函数大写(str) { Const word = []; For (let char of str.split(' ')) { word.push(char[0].toUpperCase() + char.slice(1)) } 返回的词。加入(' '); } Console.log(大写("this is a test"));

https://lodash.com/docs/4.17.11#capitalize

使用Lodash库!!更可靠的

_.capitalize('FRED'); => 'Fred'

不使用正则表达式,仅供参考:

String.prototype.toProperCase = function() { Var =这个。分割(' '); Var结果= []; For (var I = 0;I < words.length;我+ +){ var letter = words[i].charAt(0).toUpperCase(); 结果。Push(字母+单词[i].slice(1)); } 返回的结果。加入(' '); }; console.log ( “约翰·史密斯”.toProperCase () )

这是一行解决方案,如果你想转换字符串中的每个工作,用“”分割字符串,遍历部分并将此解决方案应用到每个部分,将每个转换的部分添加到一个数组中,并与“”连接。

var stringToConvert='john'; stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join(''); console.log(stringToConvert);