2016年3月17日 星期四

Javascript basic algorithm(5)--Title Case a Sentence 將句子裡的每個字的第一個字母變大寫

Review復習: charAt(), subString(),  join()

First solution第一種解法:

Thinking process(思路):
        1.turn string into array
        2.iterate the array
        3.get first letter of each element of array and capitalize it
           get the rest letters and lowercase it.
        4. join array.

function titleCase(arr){
     var getArr = arr.split(" ");   //
     for(i=0; i< getArr.length; i++){
     getArr[i] = getArr[i].charAt(0).toUpperCase() + getArr[i].substring(1).toLowerCase();
}
    
   return getArr.join(" ");
}
titleCase("I'm a little tea pot");

沒有留言:

張貼留言