You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:实现特定规则的字符串大小写转换正则方案求助

解决驼峰字符串的自定义大小写转换问题

我懂你想要替换掉硬编码的字符串处理逻辑,用正则表达式实现符合需求的驼峰拆分与大小写规则:第一个单词首字母保持小写、剩余字母全大写,后续单词拆分后首字母可选择大写或小写。咱们直接来一步步实现这个需求。

核心正则思路

我们可以通过一个正则匹配三种不同的字符片段,再用回调函数分别处理:

  1. 第一个字符:保持小写
  2. 第一个单词的后续小写字母:全部转成大写
  3. 每个大写字母(代表新单词的起始):前面加空格,再根据需求决定首字母的大小写

方案1:后续单词首字母大写(输出 aPPLE Controller)

使用这个正则和回调函数即可:

chartID.replace(/^([a-z])([a-z]+)|([A-Z])/g, function(match, firstChar, restOfFirstWord, capLetter) {
    if (firstChar) {
        // 处理第一个单词:首字母小写,其余字母大写
        return firstChar.toLowerCase() + restOfFirstWord.toUpperCase();
    } else {
        // 处理后续单词:加空格后首字母保持大写
        return ' ' + capLetter.toUpperCase();
    }
})

方案2:后续单词首字母小写(输出 aPPLE controller)

只需要调整后续单词的处理逻辑,把首字母转成小写:

chartID.replace(/^([a-z])([a-z]+)|([A-Z])/g, function(match, firstChar, restOfFirstWord, capLetter) {
    if (firstChar) {
        return firstChar.toLowerCase() + restOfFirstWord.toUpperCase();
    } else {
        return ' ' + capLetter.toLowerCase();
    }
})

替换到你的业务代码中

把原来单独处理appleController的else分支去掉,用上面的正则逻辑统一处理所有chartID即可。修改后的完整函数示例(这里用方案1):

//download chart as pdf for blades
function saveAsPDF(ID) {
    let canvas = document.querySelector('#' + ID); //Charts ID
    //creates image
    let canvasImg = canvas.toDataURL("image/png", 1.0);
    //Changing the image file to JPEG will result in the PDF having a black background
    //creates PDF from img
    let doc = new jsPDF('landscape'); // page orientation.
    doc.setFontSize(12); //Edit the font size that appears on the PDF.
    
    // 统一用正则处理所有驼峰格式的chartID
    let formattedChartID = chartID.replace(/^([a-z])([a-z]+)|([A-Z])/g, function(match, firstChar, restOfFirstWord, capLetter) {
        if (firstChar) {
            return firstChar.toLowerCase() + restOfFirstWord.toUpperCase();
        } else {
            return ' ' + capLetter.toUpperCase();
        }
    });
    
    doc.text(15, 15, formattedChartID);
    
    doc.addImage(canvasImg, 'PNG', 10, 20, 280, 150 ); // push right, push down, stretch horizontal, stretch vertical
    doc.save( chartID +'.pdf');
}
window.saveAsPDF = saveAsPDF

这样不管是appleController还是其他驼峰格式的chartID,都会按照规则自动转换,不用再单独写硬编码分支。

正则规则解释

  • ^([a-z])([a-z]+):匹配字符串开头的第一个小写字母(捕获组1),以及后面连续的小写字母(捕获组2)
  • |([A-Z]):或者匹配任意一个大写字母(捕获组3,代表新单词的起始)
  • 回调函数通过判断捕获到的组,区分当前处理的是第一个单词的哪部分,还是后续单词的起始,分别应用对应的大小写规则

内容的提问来源于stack exchange,提问作者codingWithNikki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:37:28