最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to capitalize the last letter of each word in a string - Stack Overflow

programmeradmin1浏览0评论

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 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"

Share Improve this question edited Aug 21, 2015 at 22:26 Yes Barry 9,8565 gold badges53 silver badges74 bronze badges asked Aug 21, 2015 at 21:57 vpopevpope 731 gold badge1 silver badge5 bronze badges 6
  • 2 Do you realize that no code executes in your function AFTER the return statement? What is the desired output? – jfriend00 Commented Aug 21, 2015 at 22:00
  • You have a loop inside your function, but you return on the line before that so it never runs. – Octopus Commented Aug 21, 2015 at 22:00
  • 4 What is the output you're trying to generate? – Amit Commented Aug 21, 2015 at 22:00
  • The code you've shown doesn't have any arrays in it. – Elliot Bonneville Commented Aug 21, 2015 at 22:00
  • 1 "Party Like Its 2015" - is this desired output? – sinisake Commented Aug 21, 2015 at 22:01
 |  Show 1 more comment

8 Answers 8

Reset to default 4

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.

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

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

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

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

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.



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"

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

发布评论

评论列表(0)

  1. 暂无评论