在javascript中大写字符串的一部分

问题描述

我正在尝试分割字符串并将字符串的一部分大写。但是,第一个单词的第一个字母必须保持小写。理想情况下,一个正则表达式会在将字符串拆分为下一个单词之前将字符串拆分并知道将其余单词大写。

例如:

let a = "appleController"

我需要先更改为:

'aPPLE Controller' or 'aPPLE controller'

这是完整功能,因此您可以了解其功能

//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.
    if(chartID !='appleController') {
        doc.text(15,15,chartID.replace(/^[a-z]|[A-Z]/g,function(v,i) {
            return i === 0 ? v.toupperCase() : " " + v.toLowerCase()}));
    } else {
        doc.text(15,'aPPLE Controller'); //eMAR Signoffs gets it own casing
    }
    doc.addImage(canvasImg,'PNG',10,20,280,150 ); // push right,push down,stretch horizontal,stretch vertical
    doc.save( chartID +'.pdf');
}

window.saveAsPDF = saveAsPDF

目前,“ aPPLE控制器”已进行硬编码,但理想情况下,我希望它与上述正则表达式的工作方式类似。

解决方法

好的,这样的事情怎么样?

let a = "appleController"
b = a.replace(/([A-Z])/g,' $1'); //b = "apple Controller"
let [firstWord,...rest] = b.split(" ") // firstWord = "apple"
let firstLetterAsLowerCase = firstWord.substr(0,1).toLowerCase() // a
let firstWordWithoutFirstLetterAsUpperCase = firstWord.substr(1).toUpperCase() //PPLE
let result = firstLetterAsLowerCase.concat(firstWordWithoutFirstLetterAsUpperCase).concat(" ").concat(rest) // aPPLE Controller
console.log(result)