JS Problems geeksforgeeks Exercises and Solutions for Beginners

How to Capitalize the First Letter of a String in JavaScript 📌[All Method]️

The step-by-step guide on this page will show you How to Capitalize the First Letter of a String in JavaScript. Error found! Why this could be happening? know and Learn everything.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Capitalize the First Letter of a String in JavaScript. Question: What is causing this error and what can be done to fix it? Answer: Check out this blog for a solution to your problem.

How can we capitalize just the first letter of a string?

CSS gives us the ability to apply text-transform: capitalize; to DOM text elements, but what if we need to capitalize strings in JavaScript?

Given a string s, we would first need to obtain the first letter of the string.

let s = "corgi";
s.charAt(0); // 'c'

And then capitalize that letter.

s.charAt(0).toUpperCase(); // 'C'

We then need to obtain the rest of the word.

s.slice(1); // 'orgi'

And then tack it on.

s.charAt(0).toUpperCase() + s.slice(1); // 'Corgi'

Let’s put this all together into a function. We’ll also add an extra check for non-string types.

const cap = (s) => {
  if (typeof s !== "string") return "";
  return s.charAt(0).toUpperCase() + s.slice(1);
};
cap('corgi'); // 'Corgi'
cap('shih tzu'); // 'Shih tzu'
cap(''); // ''

We can also add this function to the String prototype.

String.prototype.cap = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
};
'corgi'.cap() // 'Corgi'
'shih tzu'.cap() // 'Shih tzu'
''.cap() // ''


Revise the code and make it more robust with proper test case and check an error there before implementing into a production environment.
If you need help at any point, please send me a message and I will do my best to assist you.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button