How to capitalize the last letter of each word in a string

Issue

I am still rather new to JavaScript and I am having an issue of getting the first character of the string inside the array to become uppercase.

I have gotten to a point where I have gotten all the texted lowercase, reversed the text character by character, and made it into a string. I need to get the first letter in the string to uppercase now.

function yay () {
  var input = "Party like its 2015";

  return input.toLowerCase().split("").reverse().join("").split(" ");
  for(var i = 1 ; i < input.length ; i++){
    input[i] = input[i].charAt(0).toUpperCase() + input[i].substr(1);
  }   
}

console.log(yay());

I need the output to be “partY likE itS 2015”

Solution

Instead of returning the result splitting and reversing the string, you need to assign it to input. Otherwise, you return from the function before doing the loop that capitalizes the words.
Then after the for loop you should return the joined string.

Also, since you’ve reverse the string before you capitalize, you should be capitalizing the last letter of each word. Then you need to reverse the array before re-joining it, to get the words back in the original order.

function yay () {
  var input = "Party like its 2015";

  input = input.toLowerCase().split("").reverse().join("").split(" ");
  for(var i = 1 ; i < input.length ; i++){
    var len = input[i].length-1;
    input[i] = input[i].substring(0, len) + input[i].substr(len).toUpperCase();
  }
  return input.reverse().join(" ");
}

alert(yay());

Answered By – Barmar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published