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 a
Here is a quick code snippet. This code snippet will allow you to capitalize the first letter of a string using JavaScript.
function CapitlizeString(word)
{
return word.charAt(0).toUpperCase() + word.slice(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(' ');
};
trim()
to remove whitespace from the leading and trailing endsreplace 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
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
.
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;
}
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.
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');