0

Let's say that I have an object called "animal" and it has an attribute called "type".

By default animal.type returns string values such as "dog" or "CAT". I would like to turn those strings into something like "Dog" or "Cat" with only the first letter being uppercase. There are only alphabetic characters in the string so there will not be spaces, numbers or special characters.

What are some efficient ways to do that in JavaScript?

M. Slomski
  • 117
  • 7
  • 2
    Possible duplicate of [How do I make the first letter of a string uppercase in JavaScript?](http://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript) – wyattis Oct 03 '16 at 21:31

2 Answers2

1

Suggested duplicate is a step in the right direction, but not quite what you wanted. Try this:

function capitalize(s) {
  return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
}

console.log(['dog', 'CAT'].map(capitalize));
Community
  • 1
  • 1
Amit
  • 45,440
  • 9
  • 78
  • 110
0

You could format the string like so:

str = str[0].toUpperCase() + str.toLowerCase().substr(1);
  • 1
    `str = str.toLowerCase(); str[0] = str[0].toUpperCase()` is just as effective and vastly easier – Hamms Oct 03 '16 at 21:37