【问题标题】:Capitalize first letter of a camelcase string in Javascript在Javascript中将驼峰字符串的第一个字母大写
【发布时间】:2018-03-17 07:18:53
【问题描述】:
我正在尝试获取驼峰式字符串(但首字母大写)。
我在 JavaScript 中使用以下正则表达式代码:
String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
但第一个字母被转换为小写。
【问题讨论】:
标签:
javascript
camelcasing
【解决方案1】:
String.prototype.toCamelCase = function() {
string_to_replace = this.replace(/^([A-Z])|\s(\w)/g,
function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
return string_to_replace.charAt(0).toUpperCase() + string_to_replace.slice(1);
}
一种简单的方法是手动将第一个字符大写!
【解决方案2】:
我不鼓励在 JavaScript 中扩展 String,但无论如何要返回带有第一个大写字母的字符串,您可以这样做:
String.prototype.toCamelCase = function() {
return this.substring(0, 1).toUpperCase() + this.substring(1);
};
演示:
String.prototype.toCamelCase = function() {
return this.substring(0, 1).toUpperCase() + this.substring(1);
};
var str = "abcde";
console.log(str.toCamelCase());
【解决方案3】:
String.prototype.toCamelCase = function() {
return this.replace(/\b(\w)/g, function(match, capture) {
return capture.toUpperCase();
}).replace(/\s+/g, '');
}
console.log('camel case this'.toCamelCase());
console.log('another string'.toCamelCase());
console.log('this is actually camel caps'.toCamelCase());