Capitalize input text in Javascript

本小妞迷上赌 提交于 2019-12-02 21:15:40

问题


In a form, I have two buttons to transform text to uppercase and lowercase. I am using this function to transform input text to upper case:

document.xyz.textinput.value=document.xyz.textinput.value.toUpperCase()

Now, I want to add a new button to capitalize each word. Is it possible to achieve this with the following code?

document.xyz.textinput.value=document.xyz.textinput.value.capitalize()

Thanks


回答1:


Try This:

document.xyz.textinput.value = document.xyz.textinput.charAt(0).toUpperCase() + document.xyz.textinput.slice(1);

If you want a capitalize functions, See here.




回答2:


CSS has some text-transform properties too: https://developer.mozilla.org/en/CSS/text-transform

If that isnt an option, you can simply split your string by each whitespace and capitalize that word.




回答3:


String.prototype.capitalize = function (strSentence) {
        return strSentence.toLowerCase().replace(/\b[a-z]/g, convertToUpper);

        function convertToUpper() {
            return arguments[0].toUpperCase();
        }
}

Use this:

"hello world".capitalize();  // "Hello World"


来源:https://stackoverflow.com/questions/7951464/capitalize-input-text-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!