我是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);
};
};
答案 0 :(得分:0)
Reg exps让这个世界变得更好: - )
function convert(s,capFirstOnly) {
return s.replace(capFirstOnly ? /\b\w/ : /\b\w/g, function(a) {return a.toUpperCase(); });
}
答案 1 :(得分:0)
更好地利用这个:
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);