Javascript - 首字母大写,其余小写

时间:2016-06-18 18:13:39

标签: javascript string html5 uppercase lowercase

我需要转换字符串,首字母大写,其余全部小写,以存储在我的数据库中。

例如,用户输入

name="john";

我需要把它变成

name="John"; 

1 个答案:

答案 0 :(得分:0)

这是一个简单的脚本,可以让你这样做。

<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事件,以获得更直接的结果。

相关问题