32

I'm learning how to capitalize the first letter of each word in a string and for this solution I understand everything except the word.substr(1) portion. I see that it's adding the broken string but how does the (1) work?

function toUpper(str) {
return str
    .toLowerCase()
    .split(' ')
    .map(function(word) {
        return word[0].toUpperCase() + word.substr(1);
    })
    .join(' ');
 }
 console.log(toUpper("hello friend"))
RomeP
  • 459
  • 1
  • 4
  • 8

19 Answers19

41

The return value contain 2 parts:

return word[0].toUpperCase() + word.substr(1);

1) word[0].toUpperCase(): It's the first capital letter

2) word.substr(1) the whole remain word except the first letter which has been capitalized. This is document for how substr works.

Refer below result if you want to debug:

function toUpper(str) {
return str
    .toLowerCase()
    .split(' ')
    .map(function(word) {
        console.log("First capital letter: "+word[0]);
        console.log("remain letters: "+ word.substr(1));
        return word[0].toUpperCase() + word.substr(1);
    })
    .join(' ');
 }
 console.log(toUpper("hello friend"))
Ngoan Tran
  • 1,507
  • 1
  • 13
  • 17
18

Or you could save a lot of time and use Lodash

Look at
https://lodash.com/docs/4.17.4#startCase -added/edited-
https://lodash.com/docs/4.17.4#capitalize

Ex.

-added/edited-
You may what to use startCase, another function for capitalizing first letter of each word.

_.startCase('foo bar'); 
// => 'Foo Bar'

and capitalize for only the first letter on the sentence

_.capitalize('FRED');
// => 'Fred'

Lodash is a beautiful js library made to save you a lot of time.

There you will find a lot of time saver functions for strings, numbers, arrays, collections, etc.

Also you can use it on client or server (nodejs) side, use bower or node, cdn or include it manually.

Pablo Palacios
  • 2,767
  • 20
  • 37
  • This will only make the first letter of the whole string capital `_.capitalize('first second') // => 'First second'`, and the question states that he wants each word to start with a capital letter. if you meant to replace just the first letter, you should specify that this is not a full solution – Tomer Amir Oct 10 '17 at 07:59
  • That is the beauty of lodash, then you can use _.startCase('foo bar'); // Foo Bar, or for diferent results you have other function as an example _.toUpper('fooBar'); // FOOBAR – Pablo Palacios Oct 12 '17 at 15:35
  • 2
    This is the cleanest and best way for sure. Just use: `_.startCase(_.capitalize('foo bar'))` and even if you have a String like `FOO BAR`, it will transform in `Foo Bar` – Frederiko Ribeiro Nov 07 '19 at 23:36
  • this is also good if you wanna remove '-' or '/' and capitalise string – YEVY Aug 04 '20 at 12:24
13

Here is a quick code snippet. This code snippet will allow you to capitalize the first letter of a string using JavaScript.

function capitlizeText(word) 
{
    return word.charAt(0).toUpperCase() + word.slice(1);
}
Mohammad Jamal Dashtaki
  • 1,415
  • 1
  • 16
  • 23
11

The regexp /\b\w/ matches a word boundary followed by a word character. You can use this with the replace() string method to match then replace such characters (without the g (global) regexp flag only the first matching char is replaced):

> 'hello my name is ...'.replace(/\b\w/, (c) => c.toUpperCase());
'Hello my name is ...'
> 'hello my name is ...'.replace(/\b\w/g, (c) => c.toUpperCase());
'Hello My Name Is ...'

spinkus
  • 7,694
  • 4
  • 38
  • 62
7
function titleCase(str) {
  return str.toLowerCase().split(' ').map(x=>x[0].toUpperCase()+x.slice(1)).join(' ');
}

titleCase("I'm a little tea pot");
titleCase("sHoRt AnD sToUt");
Roger
  • 110
  • 2
  • 12
6

The major part of the answers explains to you how works the substr(1). I give to you a better aproach to resolve your problem

   function capitalizeFirstLetters(str){
      return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
          return letter.toUpperCase();
      })
    }

Explanation: - First convert the entire string to lower case - Second check the first letter of the entire string and check the first letter that have a space character before and replaces it applying .toUpperCase() method.

Check this example:

function capitalizeFirstLetters(str){
      return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
          return letter.toUpperCase();
      })
    }

console.log(capitalizeFirstLetters("a lOt of words separated even   much spaces "))
3

Consider an arrow function with an implicit return:

word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}` 

This will do it in one line.

Marvin Danig
  • 3,738
  • 6
  • 39
  • 71
2

Using ES6

let captalizeWord = text => text.toLowerCase().split(' ').map( (i, j) => i.charAt(0).toUpperCase()+i.slice(1)).join(' ')

captalizeWord('cool and cool')
Kh An
  • 481
  • 6
  • 13
1

substr is a function that returns (from the linked MDN) a new string containing the extracted section of the given string (starting from the second character in your function). There is a comment on the polyfill implementation as well, which adds Get the substring of a string.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1
function titlecase(str){
   let titlecasesentence = str.split(' ');
   titlecasesentence = titlecasesentence.map((word)=>{
     const firstletter = word.charAt(0).toUpperCase();
     word = firstletter.concat(word.slice(1,word.length));

     return word;
});
  titlecasesentence = titlecasesentence.join(' ');
  return titlecasesentence;
}
titlecase('this is how to capitalize the first letter of a word');
1
const capitalize = str => {
  if (typeof str !== 'string') {
    throw new Error('Invalid input: input must of type "string"');
  }

  return str
    .trim()
    .replace(/ {1,}/g, ' ')
    .toLowerCase()
    .split(' ')
    .map(word => word[0].toUpperCase() + word.slice(1))
    .join(' ');
};
  • sanitize the input string with trim() to remove whitespace from the leading and trailing ends
  • replace any extra spaces in the middle with a RegExp

  • normalize and convert it all toLowerCase() letters

  • convert the string to an array split on spaces

  • map that array into an array of capitalized words

  • join(' ') the array with spaces and return the newly capitalized string

1

Whole sentence will be capitalize only by one line

"my name is John".split(/ /g).map(val => val[0].toUpperCase() + val.slice(1)).join(' ')

Output "My Name Is John"

Zuhair Naqi
  • 1,162
  • 11
  • 21
1

A nice simple solution, using pure JavaScript. JSFiddle

function initCap(s) {
  var result = '';
  if ((typeof (s) === 'undefined') || (s == null)) {
    return result;
  }

  s = s.toLowerCase();
  var words = s.split(' ');
  for (var i = 0; i < words.length; ++i) {
    result += (i > 0 ? ' ' : '') +
      words[i].substring(0, 1).toUpperCase() +
      words[i].substring(1);
  }
  return result;
}
JosephStyons
  • 57,317
  • 63
  • 160
  • 234
0

Here is an example of how substr works: When you pass in a number, it takes a portion of the string based on the index you provided:

console.log('Testing string'.substr(0)); // Nothing different
console.log('Testing string'.substr(1)); // Starts from index 1 (position 2)
console.log('Testing string'.substr(2));

So, they are taking the first letter of each word, capitalizing it, and then adding on the remaining of the word. Ance since you are only capitalizing the first letter, the index to start from is always 1.

KevBot
  • 17,900
  • 5
  • 50
  • 68
0

In word.substr(i), the param means the index of the word. This method cuts the word from the letter whose index equals i to the end of the word. You can also add another param like word.substr(i, len), where len means the length of the character segmentation. For example: 'abcde'.substr(1, 2)bc.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Zhen.Liu
  • 11
  • 2
0
function toTitleCase(str)
{
  return str.replace(/\w\S*/g, function(txt){return 
  txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
aabiro
  • 3,842
  • 2
  • 23
  • 36
0

Just map through if an array set the first letter as uppercase and concatenate with other letters from index 1. The array isn't your case here.

const capitalizeNames = (arr) => {
arr.map((name) => {
    let upper = name[0].toUpperCase() + name.substr(1)       
    console.log(upper)
})

}

Victor Jonah
  • 11
  • 1
  • 1
0

Here's another clean way of Capitalizing sentences/names/... :

const capitalizeNames =(name)=>{
     const names = name.split(' ') // ['kouhadi','aboubakr',essaaddik']
     const newCapName = [] // declaring an empty array
   for (const n of names){
       newCapName.push(n.replace(n[0], n[0].toUpperCase()));
   }
   return newCapName.join(' ') 
}
capitalizeNames('kouhadi aboubakr essaaddik'); // 'Kouhadi Aboubakr Essaaddik'
Mrkouhadi
  • 446
  • 5
  • 14
0

You could use these lines of code:

function toUpper(str) {
return [str.split('')[0].toUpperCase(), str.split('').slice(1, str.split('').length).join("")].join("")
}

Basically it will split all characters, slice it, create a new array without the first entry/character and replace the first entry/character with an uppercase verion of the character.

(Yes, this was tested and it works on Edge, Chrome and newer versions of Internet Explorer.)

This is probably not the greatest answer, but hopefully it works well enough for you.