是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
你可以立即toLowerCase字符串,然后只是toUpperCase每个单词的第一个字母。变成了非常简单的一行:
函数titleCase(str) { 返回str.toLowerCase()。/\b\w/g, s => s. touppercase ()); } console.log (titleCase(‘钢铁侠’); console.log (titleCase(“绿巨人”);
其他回答
如果你想使用NPM库,请查看title-case:
安装:
npm install title-case --save
用法:
import { titleCase } from "title-case";
titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
这是个测试——>这是个测试
函数大写(str) { Const word = []; For (let char of str.split(' ')) { word.push(char[0].toUpperCase() + char.slice(1)) } 返回的词。加入(' '); } Console.log(大写("this is a test"));
一种方法使用减少
函数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); }
如果可以的话,我强烈建议使用开源的NPM包,这个包在typescript中工作得很好:
NPM: https://www.npmjs.com/package/title-case
Github: https://github.com/blakeembrey/change-case/tree/master/packages/title-case readme
运行npm install title-case将包添加到项目中。
使用标题大小写npm包的示例代码:
import { titleCase } from "title-case";
titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
约翰·史密斯->约翰·史密斯
'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );