将 javascript 中的部分字符串大写

Capitalise part of a string in 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, 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 Controller' 是硬编码的,但理想情况下,我希望它的完成方式与上面的正则表达式的工作方式类似。

使用 replace 的回调参数:

let a = "appleController"

let res = a.replace(/^[a-z]+/, m => m[0] + m.slice(1).toUpperCase() + " ");

console.log(res);

好的,这样的怎么样?

let a = "appleController"
b = a.replace(/([A-Z])/g, ' '); //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)