Doraemon 24 Doraemon 24 - 3 months ago 14
HTML Question

How to capitalize each word of an <input> using javascript?

i am try some code got it from here but it is capitalizing just the first word of the sentence

function capitalize(textboxid, str) {
// string with alteast one character
if (str && str.length >= 1)
{
var firstChar = str.charAt(0);
var remainingStr = str.slice(1);
str = firstChar.toUpperCase() + remainingStr + " ";
}
document.getElementById(textboxid).value = str;
}

<input name="sentence"id="sentencebox" onkeyup="javascript:capitalize(this.id, this.value);" placeholder="Write a Sentence" class="form-control" type="text">

Answer

If i understand correctly, this will replace any word with 2+ characters in it, if you dont want that just replace the regex with /\b([a-z])[a-z]*?/gi

function capitalize(inputField) {
  inputField.value = inputField.value.replace(/\b[a-z](?=[a-z]{2})/gi, function(letter) {
    return letter.toUpperCase();
  });
}
<input name="sentence" id="sentencebox" onkeyup="javascript:capitalize(this);" placeholder="Write a Sentence" class="form-control" type="text">

P.S. you can just use css to achieve the same effect:

#senterncebox:first-letter {
   text-transform: uppercase;
}

css is neater in my opinion, since pressing shortcuts like (ctrl+a) simply works out of the box.

Comments