-2

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.

  • I'm not very clear on what you're trying to achieve here, so far I get that you wan to split the words by the first capital letter, and add a space (You're already doing that with your regex) so, you want to capitalize the rest of the first word? or what's the pattern exactly? is swapping the case what you're looking for? https://stackoverflow.com/questions/24471618/swap-case-on-javascript – mbkfa93 Sep 29 '20 at 10:33

2 Answers2

2

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

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)
mbkfa93
  • 126
  • 2
  • 6