Doraemon 24
Doraemon 24

Reputation: 69

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">

Upvotes: 1

Views: 921

Answers (3)

Irfan Anwar
Irfan Anwar

Reputation: 1918

This is another way to capitalize first letter of each word

function capitalize(obj) {
  str = obj.value;
  obj.value = str.replace(/\w\S*/g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
}
<input name="sentence" id="sentencebox" onkeyup="javascript:capitalize(this);" placeholder="Write a Sentence" class="form-control" type="text">

Upvotes: 2

Bamieh
Bamieh

Reputation: 10936

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.

Upvotes: 1

Rob M.
Rob M.

Reputation: 36521

You should split the string on spaces and run the same basic logic against each element and join again using ' ':

var capitalized = "the quick brown fox".split(' ').map(function(word) {
    return word[0].toUpperCase() + word.slice(1)
}).join(' ');
console.log(capitalized)

Upvotes: 1

Related Questions