在输入框中将第一个字母转换为大写 [英] Convert first letter to uppercase on input box

查看:647
本文介绍了在输入框中将第一个字母转换为大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JS Bin演示

正则表达式将每个小写字词转换为大写字母。我有一个全名输入字段。我希望用户看到他/她按下的每个单词的第一个字母在输入字段中转换为大写。

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);
});


推荐答案

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

或:

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

这篇关于在输入框中将第一个字母转换为大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆