简体   繁体   中英

Javascript function to capitalize the first letter of each word

I am new to javascript so I wrote my first useful function.

FUNCTION NAME capFirstLetter()
Converts the first letter of each word in a string to uppercase.
Using the the letter "l" as the second function parameter the function will convert only the letter of the first word to uppercase.

If it has short comings of any kind please leave me a comment!

function capFirstLetter(string,capFirstOnly) {
    var i, c = "";

    if (capFirstOnly == "l") {
        var str = string.toLowerCase().trim();
        c = str.charAt(0).toUpperCase() + str.slice(1);
        return(c);
    } else {            
        c = string.charAt(0).toUpperCase().trim();
        for (i = 1; i < string.length; i++ ) {
            if (string.charAt(i) == " ") {
                c = c + string.charAt(i);
                c = c + string.charAt(i + 1).toUpperCase();
                i++;
            } else {c = c + string.charAt(i).toLowerCase();} ;
        };

        return(c);
    };
};

Reg exps make this world better :-)

function convert(s,capFirstOnly) {       
   return s.replace(capFirstOnly ? /\b\w/ : /\b\w/g, function(a) {return a.toUpperCase(); });
}

Better use this:

str="Javascript function to capitalize the first letter of each word";
    s=str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
alert(s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM