先看效果图
1 //把首字母变大写 2 function firstToUpperCase(id) { 3 var str=document.getElementById(id).value; 4 //通过“空格”符来分割成数组 5 var arr=str.toLowerCase().split(" ");// ["aq","","tn"] 6 let neweArr=[]; 7 for (var i=0; i<arr.length;i++) { 8 if (arr[i]!="") {// 不为空则把首字母大写,后面的截取出来不变 9 //arr[i][0] 相当于二维数组了 ["aq"]=>["Aq"] 10 neweArr.push(arr[i][0].toUpperCase()+arr[i].substr(1)); 11 }else { 12 neweArr.push(arr[i]); 13 } 14 } 15 var showArr=neweArr.join(" "); 16 document.getElementById(id).value=showArr; 17 }
<input onkeyup="firstToUpperCase(this.id)" type="text" class="form-control" id="userNameEn" name="userNameEn" placeholder="如:Linda Wang" value="${model.userNameEn}">