loading...

Capitalize first letter in every sentence?

github logo Updated on ・1 min read

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

twitter logo DISCUSS (7)
markdown guide
 

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

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

i think you should use slice instead of substr

function toUpper(str) {
   return str
            .toLower()
            .spilt(" ")
            .map(word => word[0] + word.slice(1))
            .join("")
}     
 

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.

 

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"
 

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

 

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

Classic DEV Post from Oct 1 '19

Daily Hacktoberfest Miscellaneous discussion (October 1st)

ivkeMilioner profile image