Attila Egyed Attila Egyed - 1 month ago 8
Javascript Question

Convert first letter to uppercase on input box

JS Bin demo

This regex transform each lower case word to upper case. I have a full name input field. I do want the user to see that each word's first letter he/she pressed is converted to uppercase in the input field.

I have no idea how to properly replace the selected characters in the current input field.

$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;

val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});

// I want this value to be in the input field.
console.log(val);
});

Answer
val = val.substr(0, 1).toUpperCase() + val.substr(1);

or:

val = val.charAt(0).toUpperCase() + val.substr(1);
Comments