If you have a string in javascript and you want to the first letter to be uppercase / a capital then this line of code will do that for you:
str = str.slice(0,1).toUpperCase() + str.slice(1);
If you want to convert more than one letter then you might want to use the following. As examples if you wanted the first 4 characters uppercase use (0,3) and then (4) and if you wanted the first 2 uppercase you would use (0,1) and then (2)
str = str.slice(0,3).toUpperCase + str.slice(4);
Remember that an array starts at zero so always take one from the numbers you want.
Thanks for the quick tip 🙂
Thanks, this tip saved me time 😉
Thanks for quick help
Thanks Harry!
Thanks a lot, I save a lot of time
Thanks for the quick tip!
Bang on. Thumbs up.!
Thanks! this save me a lot of hours, nicely done!
Hi! Great tip but did you know that .slice() is actually quite a bit slower than .charAt(0) ?
I’ve put together a list of different approaches to this problem on my blog, including a speedtest for each one of them. You can find the fastest way to convert the first letter to uppercase here:
http://forwebonly.com/capitalize-the-first-letter-of-a-string-in-javascript-the-fast-way/