How to capitalize the first letter of a string in JavaScript

Last updated on November 26th, 2024 at 12:19 pm

This JavaScript function capitalizes the first letter of each word in a given string and assigns the result to an input element

That being said lets take a look at how this script looks like,

function toUpper(myString) {
    // Capitalize each word using map
    const newString = myString.split(' ')
                              .map(word => word.charAt(0).toUpperCase() + word.slice(1))
                              .join(' ');

    // Update the input field with id 'keyword'
    document.getElementById('keyword').value = newString;

    return true; // For compatibility with form submissions
}

Using map:

  • This simplifies transforming each word in the array.

charAt and slice:

  • charAt(0) and slice(1) improve readability compared to substring.

Assuming there’s an input field with the ID keyword,

<input type="text" id="keyword" value="">
<button onclick="toUpper(document.getElementById('keyword').value)">Capitalize</button>

DEMO

1 Comment

  1. SHAFI

    Thanq So Much ….It Helps me alot