VOOZH about

URL: https://dzone.com/articles/capitalize-first-letter-string-javascript

⇱ How to Capitalize First Letter of String in JS


Related

  1. DZone
  2. Coding
  3. JavaScript
  4. How to Capitalize the First Letter of a String in JavaScript [Snippets]

How to Capitalize the First Letter of a String in JavaScript [Snippets]

A small and practical tutorial on building code for this handy little function.

By Updated Aug. 27, 19 · Code Snippet
Likes
Comment
Save
375.2K Views

Join the DZone community and get the full member experience.

Join For Free

Here is a quick code snippet for the JavaScript version of ucfirst. This code snippet will allow you to capitalize the first letter of a string using JavaScript.

function jsUcfirst(string) 
{
 return string.charAt(0).toUpperCase() + string.slice(1);
}

This code snippet will use the JavaScript function charAt to get the character at a certain index.

var firstLetter = string.charAt(0);

Next, we use the uppercase function in JavaScript to set this string to be in capitals.

var uppercaseFirstLetter = string.charAt(0).toUpperCase();

Then we can add the rest of the string on to this capital letter by using the function slice() which will allow us to get the rest of the string and remove the first letter.

var stringWithoutFirstLetter = string.slice(1)

Putting this all together, we get the JavaScript ucfirst() alternative.

function jsUcfirst(string) 
{
 return string.charAt(0).toUpperCase() + string.slice(1);
}
JavaScript Strings Data Types Snippet (programming)

Published at DZone with permission of Paul Underwood. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • JavaScript Type Conversion and Coercion
  • Adding Two Hours in DataWeave: Mule 4
  • What's New in Mule 4.4 - With Example
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: