vpope
vpope

Reputation: 73

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

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"

Upvotes: 5

Views: 11857

Answers (8)

montu48
montu48

Reputation: 26

You can split and then map over the array perform uppercase logic and retun by joining string.

let string = "Party like its 2015";

const yay = (string) => {
    let lastCharUpperCase = string.split(" ").map((elem) => {
         elem = elem.toLowerCase();
        return elem.replace(elem[elem.length - 1], elem[elem.length - 1].toUpperCase())
    })
    return lastCharUpperCase.join(" ");
}

console.log(yay(string))

Upvotes: 0

ramya sri
ramya sri

Reputation: 21



function yay(str)
{
let arr = str.split(' ');
let farr = arr.map((item) =>{
  let x = item.split('');
  let len = x.length-1
  x[len] = x[len].toUpperCase();
  x= x.join('')
  return x;
})
return farr.join(' ')

}


var str = "Party like its 2015";
let output = yay(str);

console.log(output) /// "PartY likE itS 2015"

Upvotes: 0

Dave
Dave

Reputation: 10924

Here's what I would do:

  1. Split the sentence on the space character
  2. Transform the resulting array using .map to capitalize the first character and lowercase the remaining ones
  3. Join the array on a space again to get a string

function yay () {
  var input = "Party like its 2015";
  return input.split(" ").map(function(item) {
    return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
  }).join(" ");
}

console.log(yay());

Upvotes: 1

jfriend00
jfriend00

Reputation: 708016

Frustrating that you posted your initial question without disclosing the desired result. Lots of turmoil because of that. Now, that the desired result is finally clear - here's an answer.

You can lowercase the whole thing, then split into words, rebuild each word in the array by uppercasing the last character in the word, then rejoin the array:

function endCaseWords(input) {
    return input.toLowerCase().split(" ").map(function(item) {
        return item.slice(0, -1) + item.slice(-1).toUpperCase();
    }).join(" ");
}

document.write(endCaseWords("Party like its 2015"));

Here's a step by step explanation:

  1. Lowercase the whole string
  2. Use .split(" ") to split into an array of words
  3. Use .map() to iterate the array
  4. For each word, create a new word that is the first part of the word added to an uppercased version of the last character in the word
  5. .join(" ") back together into a single string
  6. Return the result

You could also use a regex replace with a custom callback:

function endCaseWords(input) {
    return input.toLowerCase().replace(/.\b/g, function(match) {
      return match.toUpperCase();
    });
}

document.write(endCaseWords("Party like its 2015"));

FYI, there are lots of things wrong with your original code. The biggest mistake is that as soon as you return in a function, no other code in that function is executed so your for loop was never executed.

Then, there's really no reason to need to reverse() the characters because once you split into words, you can just access the last character in each word.

Upvotes: 4

Barmar
Barmar

Reputation: 782488

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

Upvotes: 3

Yes Barry
Yes Barry

Reputation: 9876

Try using ucwords from PHP.js. It's quite simple, actually.

String.prototype.ucwords = function() {
    return (this + '')
        .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
        return $1.toUpperCase();
    });
}

var input = "Party like its 2015";
input = input.charAt(0).toLowerCase() + input.substr(1);
input = input.split('').reverse().join('').ucwords();
input = input.split('').reverse().join('');

Note: I modified their function to be a String function so method chaining would work.

Upvotes: 0

sinisake
sinisake

Reputation: 11338

Some ugly, but working code:

 var text = "Party like its 2015";
  //partY likE itS 2015
  function yay(input) {

    input = input.split(' ');

    arr = [];

    for (i = 0; i < input.length; i++) {
      new_inp = input[i].charAt(0).toLowerCase() + input[i].substring(1, input[i].length - 1) + input[i].charAt(input[i].length - 1).toUpperCase();
      arr.push(new_inp);
    }

    str = arr.join(' ');
    return str;

  }

  console.log(yay(text));

Upvotes: 0

ZER0
ZER0

Reputation: 25332

You can use regular expression for that:

input.toLowerCase().replace(/[a-z]\b/g, function (c) { return c.toUpperCase() });

Or, if you can use arrow functions, simply:

input.toLowerCase().replace(/[a-z]\b/g, c => c.toUpperCase())

Upvotes: 3

Related Questions