0

I was writing a test function to capitalize each word in a sentence. I ended up solving it; however, one of my first attempts to solve the problem didn't work when I thought it would.

function capSentence(str) { 
  var strArray = str.split(" ");
  var answer = '';
  var temp = '';
  for(var i = 0; i < strArray.length; i++){
    strArray[i][0] = strArray[i][0].toUpperCase();
    answer += strArray[i];
    if(i !== strArray.length-1){
      answer += ' ';
    }
  }
  return answer; 

}

capSentence("this is a test");

I thought the above code would output "This Is A Test", but instead it outputs "this is a test".

strArray[i][0] = strArray[i][0].toUpperCase();

doesn't seem to have any affect. Why is that?

2

3 Answers 3

1

@thefourtheye's comment is correct. You need to build a new string.

function capSentence(str) { 
  var strArray = str.split(" ");
  var answer = '';
  var temp = '';

  for(var i = 0; i < strArray.length; i++){
      answer += strArray[i][0].toUpperCase();
      answer += strArray[i].slice(1,strArray[i].length);

      if(i !== strArray.length-1){
        answer += ' ';
      }
   }

   return answer;

}
Sign up to request clarification or add additional context in comments.

Comments

0

Strings are immutable in Javascript. That's why you are not able to change the value of the strArray.

But you can do in this way:

function capSentence(str) { 
  strArray = str.split(" ");
  console.log(strArray);
  var answer = '';
  var temp = '';
  for(var i = 0; i < strArray.length; i++){

    for (var j = 0; j< strArray[i].length; j++) {
       if(j==0) {
          temp = strArray[i][j].toUpperCase();
       }  else {
         temp+=strArray[i][j];
       }
    }

    answer += temp;
    if(i !== strArray.length-1){
      answer += ' ';
    }
  }
  return answer; 

}

This will retrun "This Is A Test"

Comments

0

Try this simple snippet,

function capSentence(str) {
 var strArray = str.split(" ");
 var answer = '';
 var temp = '';
 for(var i = 0; i < strArray.length; i++){
  answer += (strArray[i].substring(0,1)).toUpperCase()+strArray[i].substring(1);
  if(i !== strArray.length-1){
   answer += ' ';
  }
 }
 return answer;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.