如何在JavaScript中将类似'helloThere‘或'HelloThere’的字符串转换为'Hello There‘?
发布于 2011-08-29 10:11:46
const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);
以第一个字母大写为例。请注意" $1"中的空格。
当然,如果第一个字母已经是大写的,那么您将有多余的空间可以删除。
发布于 2016-07-28 19:49:22
或者使用lodash
lodash.startCase(str);示例:
_.startCase('helloThere');
// ➜ 'Hello There'Lodash是一个很好的库,可以为许多日常的js和许多其他类似的字符串操作函数,如camelCase,kebabCase等提供快捷方式。
发布于 2011-08-29 10:17:07
我遇到了类似的问题,并像这样处理它:
stringValue.replace(/([A-Z]+)*([A-Z][a-z])/g, "$1 $2")要获得更强大的解决方案:
stringValue.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1")http://jsfiddle.net/PeYYQ/
输入:
helloThere
HelloThere
ILoveTheUSA
iLoveTheUSA输出:
hello There
Hello There
I Love The USA
i Love The USAhttps://stackoverflow.com/questions/7225407
复制相似问题