DEV Community

ivkeMilioner
ivkeMilioner

Posted on • Updated on

Capitalize first letter in every sentence?

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

Top comments (7)

Collapse
 
anwar_nairi profile image
Anwar • Edited

If you check the prototype of substr (see the MDN documentation), you can see that there is this second optional parameter length:

String.prototype.substr = function(start: number, length: number = undefined): string

And the documentation states that

If length is omitted, substr() extracts characters to the end of the string.

So when you call word.substr(1), this is the equivalent of:

word.substr(1, word.length);
Collapse
 
savagepixie profile image
SavagePixie • Edited

word.substr(1) is creating a new string from word starting on the character at index 1. So it's basically the whole word except the first character.

Example:

const str = "potato"
const newStr = str.substr(1) // = "otato"
Collapse
 
ryansmith profile image
Ryan Smith

If you are trying to find an effective way to do this and your app uses CSS for a front-end, you can use text-transform: capitalize; to do it.

But if it is just for a JavaScript-only app or practice, the other comments will be more helpful.

Collapse
 
alibasiccoder profile image
AliBasicCoder • Edited

i think you should use slice instead of substr

function toUpper(str) {
   return str
            .toLower()
            .spilt(" ")
            .map(word => word[0] + word.slice(1))
            .join("")
}     
Collapse
 
daxsoft profile image
Michael Willian Santos • Edited

Well, try to regex: (good site to practice is regex101.com/)

const capitalizeFirstLetters = (str) => str.replace(/(\b([a-z]))/gi, (str) => str.toUpperCase())

Now, some funny but not recommendend for this case alone:

const funnyWay = str => str.split(/\b/gi).map(char => char.replace(/^\w{1}/i, (letter) => letter.toUpperCase())).join('')
Collapse
 
stevematdavies profile image
Stephen Matthew Davies • Edited

Perhaps consider looking at regex and groupings. With regex you can target each single letter that falls after a whitespace, you can do this via the String replace() function. Then there is no need to split iterate and join.

developer.mozilla.org/en-US/docs/W...

Collapse
 
devdrake0 profile image
Si

Regex is indeed powerful, but I wouldn't recommend a beginner try to learn it.