Capitalise part of a string in javascript

92 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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);

0
On

Ok, How about something like this?

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)