Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
How to refactor this code to make it work (JS)?

The objective of this problem is to replace each first Letter of the word in a paragraph.Here is my code.

function isAlphabet(char){
return (/[a-z]/).test(char);
}

// TODO: Implement this method
function capitalise(paragraph) {
if (paragraph.length===1){
  return paragraph.toUpperCase();
}



  paragraph=paragraph.charAt(0).toUpperCase()+paragraph.slice(1);
  for(let i=2;i<paragraph.length;i++){

    if(paragraph[i-1]==' ' && isAlphabet(paragraph[i])){
      let char_new=String.fromCharCode(paragraph.charCodeAt(i)-32)

     paragraph[i] = char_new;

    }

  }

  return paragraph;
  
}

However I get the following error when I am writing up this line of code:

let char_new=String.fromCharCode(paragraph.charCodeAt(i)-32)
paragraph[i] = char_new; 

and the error says :

/sidharthgopalakrishnan-ME_PE_PROGRAMMING_CONSTRUCTS_NEW-bba4832c-4354-4df8-b7e5-b0340a954783/user/Capitalise.js:59 paragraph[i] = char_new; ^ TypeError: Cannot assign to read only property '4' of string 'The quick Brown fox jumps over The lazy dog.'

What I wanted to know was what is TypeError ? and what does a read only property mean ?This is something I want more insight in and lastly what I can do to make this code work in javascript ?

Thanks and Regards

Update: Here is what I tried further:

function isAlphabet(char) {
  return /[a-z]/.test(char);
}
function capitalise(paragraph) {
  if (paragraph.length === 1) {
    return paragraph.toUpperCase();
  }

  let new_para = paragraph.charAt(0).toUpperCase() + paragraph.slice(1);

  for (let i = 2; i < paragraph.length; i++) {
    if (paragraph[i - 1] == " " && isAlphabet(paragraph[i])) {
      // console.log(String.fromCharCode(paragraph.charCodeAt(i) - 32));

      let new_para = paragraph.replace(
        paragraph[i],
        String.fromCharCode(paragraph.charCodeAt(i) - 32)
      );

      console.log(new_para)
    }
  }

  return new_para;
}




However the change isn't being assigned onto the variable I have set it to , through each iteration the respective first letter gets capitalised but it doesnt affect the original state. Can someone help me with this further ?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!