Uppercase first letter of variable

后端 未结 23 1364
粉色の甜心
粉色の甜心 2020-11-30 20:55

I have searched over the web can can\'t find anything to help me. I want to make the first letter of each word upper case within a variable.

So far i have tried:

相关标签:
23条回答
  • 2020-11-30 21:17

    It is as simple as the following:

    string = 'test';
    newString = string[0].toUpperCase() + string.slice(1);
    alert(newString);
    
    0 讨论(0)
  • 2020-11-30 21:17

    I have used this code -

    function ucword(str){
        str = str.toLowerCase().replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(replace_latter) { 
            return replace_latter.toUpperCase();
        });  //Can use also /\b[a-z]/g
        return str;  //First letter capital in each word
    }
    
    var uc = ucword("good morning. how are you?");
    alert(uc);
    
    0 讨论(0)
  • 2020-11-30 21:17

     var str = "HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD";
             str = str.replace(
                            /([A-Z])([A-Z]+)/g,
            				function (a, w1, w2) {
                                return w1 + w2.toLowerCase();
                            });
    alert(str);

    0 讨论(0)
  • 2020-11-30 21:20

    The string to lower before Capitalizing the first letter.

    (Both use Jquery syntax)

    function CapitaliseFirstLetter(elementId) {
        var txt = $("#" + elementId).val().toLowerCase();
        $("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
        return $1.toUpperCase(); }));
        }
    

    In addition a function to Capitalise the WHOLE string:

    function CapitaliseAllText(elementId) {
         var txt = $("#" + elementId).val();
         $("#" + elementId).val(txt.toUpperCase());
         }
    

    Syntax to use on a textbox's click event:

    onClick="CapitaliseFirstLetter('TextId'); return false"
    
    0 讨论(0)
  • 2020-11-30 21:23

    Simplest way

    let str="hiren raiyani"
    str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
    

    user-defined function:

    function capitalize(str){
     return str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
    }
    

    output: Hiren Raiyani

    Use code as your user-defined function or direct

    0 讨论(0)
提交回复
热议问题