gpt4 book ai didi

javascript - 在 Javascript 中将驼峰字符串的首字母大写

转载 作者:行者123 更新时间:2023-11-30 11:30:03 25 4
gpt4 key购买 nike

我正在尝试获取驼峰式字符串(但首字母大写)。

我在 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());

关于javascript - 在 Javascript 中将驼峰字符串的首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46589554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com