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


当前回答

试试这个,最短的方法:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());

其他回答

使用/\S+/g支持变音符:

function toTitleCase(str) replace str.replace(/\S+/g, str => str.charAt(0). toupbelise (str.substr, 1); 的 控制台(toTitleCase(“一个城市叫orebro”);-一个叫Orebro的城市

然而:“阳光(黄色)”⇒“阳光(黄色)”

Var结果= “这很有趣”。/\b[a-z]/g, (x) => x. touppercase ()) console.log(result) // This Is Very Interesting

使用正则表达式的一行程序,获取单词\b[A- za -z]的所有\g开头字符,并应用.toUpperCase()

const textString = "用Javascript将字符串转换为标题大小写。"; const convert = textString。替换(/ \ [a-zA-Z] b / g,(比赛)= > match.toUpperCase ()); console.log(转换)

如果可以的话,我强烈建议使用开源的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 f. kennedy".replace(/\b\S/g, t => t.toUpperCase())