Search code examples
javascriptregexcamelcasingcapitalize

Capitalise part of a string in javascript


I am trying to split a string and make part of the string capitalised. however the first letter of the first word must stay lowercase. Ideally a regex that would split the string and know to capitalise the rest of that word, before splitting the string for the next word.

for example:

let a = "appleController"

I need a to then change to:

'aPPLE Controller' or 'aPPLE controller'

Here is the full function so you can have an idea of what it is doing:

//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

Currently, ''aPPLE Controller' is hardcoded in but ideally I would like for it to done similarly to how the regex above works.


Solution

  • With a callback argument to replace:

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