原生js实现单词英文首字母大写,这是面试时经常出现的题,以下是2种解决办法:
方法一:
function wordToUpperCase(str){ var str = str.toLowerCase(); str = str.replace(/(^|\s+)\w/g,function(s){ return s.toUpperCase(); }); return str; } alert(wordToUpperCase("abc def ABC"));//结果为:Abc Def Abc
方法二:
function wordToUpperCase(str){ var str = str.toLowerCase(); var strarr = str.split(' '); var result = ''; for(var i = 0;i<strarr.length;i++){ result += strarr[i].substr(0,1).toUpperCase(); result += strarr[i].substr(1); result += " "; } return result; } console.log(wordToUpperCase("AAA bbb Ccc"));