[英]Capitalize first letter of a camelcase string in Javascript
我正在尝试获取驼峰大小写字符串(但首字母大写)。
我在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中扩展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());
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());
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);
}
一种简单的方法是手动大写第一个字符!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.