Javascript函数,用于大写每个单词的首字母
Javascript function to capitalize the first letter of each word
我是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);
相关文章:
- 如何知道找到的单词是字符串的一部分还是JavaScript中的函数调用
- JavaScript 函数.返回单词出现的次数
- 为什么javascript函数名称custom是一个小写的单词,后跟一个大写的单词,就像'orangeCost'一样
- 如何在没有javascript中的split函数的情况下将字符串拆分为单词
- 我想使用replace函数扫描json对象,然后用字符串替换匹配的单词
- 编写函数,通过1个字符的JavaScript匹配单词
- 在 javaScript 中定义函数之前,什么意思是“一个单词:”
- 在双击/选择单词时在 chrome 扩展程序中运行函数
- 在 Javascript 中触发一个函数,如果单词在字典中
- 创建一个 JavaScript 函数来反转单词
- 在angularjs ng-change=“chk(query)”中,当键入单词后点击空格时调用函数
- Javascript函数,用于大写每个单词的首字母
- JavaScript字符,单词和空格计数函数
- Javascript函数生成符合元音和辅音模式的所有可能单词的列表
- 简化工作函数以替换特定单词
- 创建一个自动完成函数,不显示每个单词
- Javascript:使用.sort和compare函数查找数组中最长的单词
- Regex函数使单词标题大小写(包括连字符)
- Polyfill/fix用于在保留的JS单词(如'函数'
- 与javascript匹配的单词函数