How to make first letter of a string uppercase using Javascript

Last updated on March 4th, 2022 at 06:18 pm

Click to rate this tutorial!
[Total: 11 Average: 3.7]

This is a simple tutorial which shows how to capitalize first alphabet or letter in a word or string using Javascript.
Say for instance you have a contact form in which it has an input field that requires the NAME of the user.
Names should always begin with CAPS and the user just like that entered his/her name in the field. Then our script will track that and automatically convert the first letter or alphabet in to uppercase.
For example if the name entered by user is gurera linda then our javascript will track this and convert the name into Gurera Linda.

Check out our tutorial on how to convert complete text to lower case using javascript

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

function toUpper(mystring) {
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1);
word[i] = f+r;
}
newstring = word.join(' ');
document.getElementById('keyword').value = newstring;
return true;
}

And how to call this javascript. Its simple just use the onblur switch and call the function like this

onblur="toUpper(this.value);"

So once this is inserted in the input tag it will look something like

<input onblur="toUpper(this.value);" autocomplete="off" id="keyword" size="50" type="text" name="txtAddManager" />

Thats all pretty simple right 🙂

DEMO

Click to rate this tutorial!
[Total: 11 Average: 3.7]

One reply on “How to make first letter of a string uppercase using Javascript”

Leave a Reply

Your email address will not be published.