将驼峰大小写文本转换为标题大小写文本

2022-08-30 01:05:15

如何在JavaScript中将“helloThere”或“HelloThere”等字符串转换为“Hello There”?


答案 1

const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);

以第一个字母大写为例。请注意 中的空格。" $1"


当然,如果第一个字母已经是大写的 - 您将有一个空闲的空间来删除。


答案 2

或者使用 lodash

lodash.startCase(str);

例:

_.startCase('helloThere');
// ➜ 'Hello There'

Lodash是一个很好的库,可以为许多日常js任务提供快捷方式。还有许多其他类似的字符串操作函数,如 等。camelCasekebabCase