首页 > 代码库 > 53.单词首字母转大写

53.单词首字母转大写

技术分享
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>转换文本-只在IE上有效</title>
 6 </head>
 7 <body>
 8 <input type="text" name="txt1" value="http://www.mamicode.com/this is text!"/>
 9 <button onclick="change(txt1)">转换文本</button>
10 <script>
11     var change = function (frmObj) {
12         var index, tmpStr, tmpChar, preString, postString;
13         tmpStr = frmObj.value.toLowerCase();  //全部转换成小写
14         strLen = tmpStr.length;
15         if (strLen > 0) {
16             for (index = 0; index < strLen; index++) {
17                 if (index == 0) {
18                     //将第一位转换成大写
19                     tmpChar = tmpStr.substring(0, 1).toUpperCase();
20                     postString = tmpStr.substring(1, strLen);
21                     tmpStr = tmpChar + postString;
22                 } else {
23                     tmpChar = tmpStr.substring(index, index + 1);
24                     //如果是第二个单词,通过空格判断
25                     if (tmpChar == ‘ ‘ && index < (strLen - 1)) {
26                         tmpChar = tmpStr.substring(index + 1, index + 2).toUpperCase();
27                         preString = tmpStr.substring(0, index + 1);
28                         postString = tmpStr.substring(index + 2, strLen);
29                         tmpStr = preString + tmpChar + postString;
30 
31                     }
32 
33                 }
34             }
35         }
36         frmObj.value = http://www.mamicode.com/tmpStr; //显示转换后的文本>
View Code

 

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>单词首字母转大写-只在IE上有效</title>
</head>
<body>
<input type="text" name="txt1" value="http://www.mamicode.com/this is text!"/>
<button onclick="change(txt1)">转换文本</button>
<script>
var change = function (frmObj) {
var index, tmpStr, tmpChar, preString, postString;
tmpStr = frmObj.value.toLowerCase(); //全部转换成小写
strLen = tmpStr.length;
if (strLen > 0) {
for (index = 0; index < strLen; index++) {
if (index == 0) {
//将第一位转换成大写
tmpChar = tmpStr.substring(0, 1).toUpperCase();
postString = tmpStr.substring(1, strLen);
tmpStr = tmpChar + postString;
} else {
tmpChar = tmpStr.substring(index, index + 1);
//如果是第二个单词,通过空格判断
if (tmpChar == ‘ ‘ && index < (strLen - 1)) {
tmpChar = tmpStr.substring(index + 1, index + 2).toUpperCase();
preString = tmpStr.substring(0, index + 1);
postString = tmpStr.substring(index + 2, strLen);
tmpStr = preString + tmpChar + postString;

}

}
}
}
frmObj.value = http://www.mamicode.com/tmpStr; //显示转换后的文本
}
</script>
</body>
</html>

53.单词首字母转大写