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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

You could format the string like so:

str = str[0].toUpperCase() + str.toLowerCase().substr(1);

1 Comment

str = str.toLowerCase(); str[0] = str[0].toUpperCase() is just as effective and vastly easier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.