我如何转换字符串既像'helloThere'或'helloThere'到'HelloThere'在JavaScript?
当前回答
使用JS的String.prototype.replace()和String.prototype.toUpperCase()
const str = "thisIsATestString"; const res = str.replace (/ ^ [a - z] | [a - z] / g (c i) = >(我吗?": "") + c.toUpperCase()); console.log (res);// "This Is A Test String"
其他回答
没有副作用的例子。
function camel2title(camelCase) {
// no side-effects
return camelCase
// inject space before the upper case letters
.replace(/([A-Z])/g, function(match) {
return " " + match;
})
// replace first char with upper case
.replace(/^./, function(match) {
return match.toUpperCase();
});
}
在ES6
const camel2title = (camelCase) => camelCase
.replace(/([A-Z])/g, (match) => ` ${match}`)
.replace(/^./, (match) => match.toUpperCase())
.trim();
基于上面的一个例子,我想出了这个:
const camelToTitle = (camelCase) => camelCase
.replace(/([A-Z])/g, (match) => ` ${match}`)
.replace(/^./, (match) => match.toUpperCase())
.trim()
它适用于我,因为它使用.trim()来处理边缘情况,其中第一个字母是大写的,并且您最终有一个额外的前导空格。
参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
你可以使用这样的函数:
function fixStr(str) {
var out = str.replace(/^\s*/, ""); // strip leading spaces
out = out.replace(/^[a-z]|[^\s][A-Z]/g, function(str, offset) {
if (offset == 0) {
return(str.toUpperCase());
} else {
return(str.substr(0,1) + " " + str.substr(1).toUpperCase());
}
});
return(out);
}
"hello World" ==> "Hello World"
"HelloWorld" ==> "Hello World"
"FunInTheSun" ==? "Fun In The Sun"
带有一堆测试字符串的代码:http://jsfiddle.net/jfriend00/FWLuV/。
保留前导空格的替代版本:http://jsfiddle.net/jfriend00/Uy2ac/。
我也遇到过类似的问题,我是这样处理的:
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 USA
连续大写单词的最兼容的答案是:
常量文本 = 'theKD'; const result = text.replace(/([A-Z]{1,})/g, “$1”); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); 控制台.log(最终结果);
它也与KD兼容,不会将其转换为KD。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- JavaScript: override alert()
- 重置setTimeout