<html>
<head>
<title>將所有英文字第一個字母變為大寫</title>
<SCRIPT LANGUAGE="JavaScript">
function changeCase(frmObj)
{
var index;
var tmpStr;
var tmpChar;
var preString;
var postString;
var strlen;
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);
//透過space判斷第二個單字
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 = tmpStr; //替換成轉換後的文字
}
</script>
</head>
<body>
<input type=text name="txt1" value="this is test!">
<input type=button value="將英文首字母變大寫" onClick="javascript:changeCase(txt1)">
</body>
</html>

 

arrow
arrow

    痞客興 發表在 痞客邦 留言(0) 人氣()