简体   繁体   中英

Capitalize first letter of each word using reduce in Javascript

The function should capitalize the first letter of each word in the string then return the capitalized string.

--- Examples

capitalize('a short sentence') --> 'A Short Sentence'

capitalize('a lazy fox') --> 'A Lazy Fox'

I got it working without using reduce but I want to be better at reduce but I can't get it to work.

capitalize = str => {
  //V1
  return str
  .split(" ")
  .map(w => {
    return w.charAt(0).toUpperCase() + w.slice(1);
  })
  .join(" ");
};

Me trying with reduce:

capitalize = str => {
    let index = 0;
      const arr = str.split("");
      return arr.reduce((acc, curr, i) => {
        console.log(acc);
        if (acc === " ") {
          return curr.toUpperCase();
        }
        index = i;
      }, arr[index]);
    };

If you wanted to use reduce here, it would probably be easiest to (similar to what you're doing originally) iterate over words rather than letters, where the accumulator is the capitalized string you're in the progress of creating. The only tricky part is checking whether you need to add a space before inserting the changed word or not:

 const capitalize = str => { const arr = str.split(" "); return arr.reduce((acc, word) => ( acc + (acc === '' ? '' : ' ') // add space before next word if necessary + word[0].toUpperCase() + word.slice(1)) , ''); }; console.log(capitalize('a short sentence')) // --> 'A Short Sentence' console.log(capitalize('a lazy fox')) // --> 'A Lazy Fox' 

Still, that's not so readable. I think .map / .join looks better.

One option would be to treat the string as a character array, and to uppercase the character if it's either the first element in the array, or if the preceding element is a space:

 const capitalize = str => [...str].reduce( (s, c, i, a) => s + (i === 0 || a[i - 1] === ' ' ? c.toUpperCase() : c), '' ); console.log(capitalize('a short sentence')); 

 function capitalize(string) { return string.split(' ').reduce((accumulatedString, currentWord) => accumulatedString.concat(currentWord[0].toUpperCase() + currentWord.slice(1)), []).join(' ') } console.log(capitalize('a lazy fox')) 

Just using CSS:

 p { text-transform: capitalize; } 
 <p>a short sentence</p> 

Using JavaScript Array.prototype.reduce() :

 const str = 'a lazy fox'; const capitalize = str => str .split(' ') .reduce((a, c) => { const word = `${c.charAt(0).toUpperCase()}${c.slice(1)}`; return a ? `${a} ${word}` : word; }, ''); console.log(capitalize(str)); 

Check this one:

 const a = 'a lazy fox'; const b = 'a short sentence'; const capitalizeAllWord = str => str && str.split(" ") .reduce((acc, curr)=> [...acc, `${curr.charAt(0).toUpperCase()}${curr.slice(1)}`] ,[]) .join(" "); console.log(capitalizeAllWord(a)); console.log(capitalizeAllWord(b)); 

Try this code .It will helps you.

  const input = 'a short sentenc' output = input.substring(0, 1).toUpperCase() + input.substring(1); console.log(output) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM