Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});
like image 652
aegyed Avatar asked Feb 04 '13 13:02

aegyed


People also ask

How do you make the first letter capital input field?

Just include → style="text-transform:capitalize;" inside your input tag. Same solution as other answers.

How do you capitalize the first letter of a input in python?

The first letter of a string can be capitalized using the capitalize() function. This method returns a string with the first letter capitalized. If you are looking to capitalize the first letter of the entire string the title() function should be used.

How do you replace the first character in a string with uppercase?

You can use str. title() to get a title cased version of the string. This converts the first character of each word in the string to uppercase and the remaining characters to lowercase.


2 Answers

Given i.e: const str = "hello world" to become Hello world

const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);

or:

const firstUpper = str.charAt(0).toUpperCase() + str.substr(1);

or:

const firstUpper = str[0] + str.substr(1);
like image 72
Roko C. Buljan Avatar answered Nov 15 '22 16:11

Roko C. Buljan


input {
    text-transform: capitalize;
}

http://jsfiddle.net/yuMZq/1/

Using text-transform would be better.

like image 38
dfsq Avatar answered Nov 15 '22 18:11

dfsq