There is no simple one-liner way of doing this. However, you can make a function which can format the name for you.
Originally taken from this answer, I've modified it slightly to reflect your desired output:
var name1 = "Lionel MESSI";
var name2 = "LiONEL MesSI";
var name3 = "Neymar JR";
var name4 = "Neymar 22 JR";
var name5 = "Franck D'HONNEUR";
var name6 = "Kevin PEREZ ROBERTO";
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/[0-9]/g, '');
}
console.log(toTitleCase(name1));
console.log(toTitleCase(name2));
console.log(toTitleCase(name3));
console.log(toTitleCase(name4));
console.log(toTitleCase(name5));
console.log(toTitleCase(name6));
You may want to check out toUpperCase() and toLowerCase() from the MDN documentation.
To get this functionality in on onKeyDown()
, you can use jQuery like the snippet below. I do advice against onKeyDown()
though as this creates a weird user experience. Try onBlur
instead.
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/[0-9]/g, '');
}
$("#name").on("keydown", function() {
$(this).val(toTitleCase($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Name: <input id="name">