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


当前回答

大多数答案似乎忽略了使用单词边界元字符(\b)的可能性。Greg Dean使用它的回答的简短版本:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

也适用于连字符的名字,如吉姆-鲍勃。

其他回答

如果你想使用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"

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

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

将单个单词转换为标题大小写的简单方法

使用“切片”方法和字符串拼接

str.slice(0, 1).toUpperCase() + str.slice(1, str.length)

*如果你想要小写单词的其余部分,在结尾添加.toLowerCase()

使用ES6扩展操作符、映射和Join

[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')

如果可以的话,我强烈建议使用开源的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"

这里有一个非常简单而简洁的ES6函数来做到这一点:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}

export default titleCase;

工作良好,包括在一个实用程序文件夹,并使用如下:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'