functionfindLongestWord(str) { var words = str.split(" "); var length = 1; words.map(function(word) { length = Math.max(length, word.length); }); return length; }
console.log(findLongestWord("The quick brown fox jumped over the lazy dog")); // 6 console.log(findLongestWord("What is the average airspeed velocity of an unladen swallow")); // 8 console.log(findLongestWord("What if we try a super-long word such as otorhinolaryngology")); // 19
5、设置首字母大写
返回一个字符串, 确保字符串的每个单词首字母都大写,其余部分小写。
1 2 3 4 5 6 7 8 9 10 11 12 13
functiontitleCase(str) { var words = str.split(" "); words = words.map(function(word) { var newWord = word.toLowerCase(); newWord = newWord.replace(newWord.charAt(0), newWord.charAt(0).toUpperCase()); return newWord; }); return words.join(" "); }
console.log(titleCase("I'm a little tea pot")); // I'm A Little Tea Pot console.log(titleCase("sHoRt AnD sToUt")); // Short And Stout console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")); // Here Is My Handle Here Is My Spout
console.log(confirmEnding("Bastian", "n")); // true console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")); // false console.log(confirmEnding("He has to give me a new name", "name")); // true console.log(confirmEnding("He has to give me a new name", "na")); // false
console.log(truncate("A-tisket a-tasket A green and yellow basket", 11)); // "A-tisket..."" console.log(truncate("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)); // "A-tisket a-tasket A green and yellow basket" console.log(truncate("A-", 1)); // "A..."
10、数组分割
编写一个函数, 把一个数组 arr 按照指定的数组大小 size 分割成若干个数组块。
1 2 3 4 5 6 7 8 9 10 11
functionchunk(arr, size) { var array = []; for (var i = 0; i < arr.length / size; ++i) { array.push(arr.slice(i * size, i * size + size)); } return array; }
functionwhere(arr, num) { arr.sort(function(a, b) { return a > b; }); for (var i = 0; i < arr.length; ++i) { if (num <= arr[i]) { return i } } return arr.length; }
functionrot13(str) { var newStr = ""; for (var i = 0; i < str.length; ++i) { if (str.charCodeAt(i) > 90 || str.charCodeAt(i) < 65) { newStr += str.charAt(i); continue; } var code = str.charCodeAt(i) + 13; if (code < 65) { code = 91 - (65 - code); } elseif (code > 90) { code = 64 + (code - 90); } newStr += String.fromCharCode(code); } return newStr; }
console.log(rot13("SERR PBQR PNZC")); // "FREE CODE CAMP" console.log(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.")); // "THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX."