Javascript函数,用于大写每个单词的首字母

Javascript function to capitalize the first letter of each word

本文关键字:单词 函数 用于 Javascript      更新时间:2023-09-26

我是javascript的新手,所以我写了我的第一个有用的函数。

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.

如果它有任何缺点,请给我留言!

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 让这个世界变得更好 :-)

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

最好使用这个:

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);