【问题标题】:Javascript - First letter uppercase, the rest lower case [duplicate]Javascript - 第一个字母大写,其余小写[重复]
【发布时间】:2016-10-20 09:21:35
【问题描述】:

我需要转换字符串,将第一个字母大写,其余所有小写,以存储在我的数据库中。

例如,用户输入

name="john";

我需要把它变成

name="John"; 

【问题讨论】:

  • 这个已经问过了,不需要重复问答。
  • 不是完全重复的,因为 OP 要求将其余部分小写 - 链接的问题仅关于大写第一个字符。显然,两者都是简单的问题,但不是重复的。不过,这里的这个问题需要澄清。
  • @MrUber 请澄清您的问题:“存储在我的数据库中”是什么意思?您是在客户端(总是可以绕过)还是服务器端寻找“实时”大写小写?
  • @le_m 是的,但这是一个问答问题,即我已经创建了所需的脚本!

标签: javascript string html uppercase lowercase


【解决方案1】:

这是一个简单的脚本,可让您执行此操作。

<input type="text" id="name" onblur="capitalize(this.id)" value="" autofocus>

<script>
    function capitalize(id)
    {
        var text = document.getElementById(id).value; //get the text
        var firstL = text.slice(0,1).toUpperCase(); //get the first character and make it Uppercase
        var rest = text.slice(1).toLowerCase(); //get the rest of the string and make it Lowercase
        var text = firstL.concat(rest); //create the new text store it
        document.getElementById(id).value = text; //set the value of the field
    }
</script>

onblur 事件可以更改为不同的事件,例如 onkeyup,以获得更直接的结果。

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多