The marketing team is spending way too much time typing in hashtags. Let’s help them with our own Hashtag Generator!
Here’s the deal:
It must start with a hashtag (#). All words must have their first letter capitalized. If the final result is longer than 140 chars it must return false. If the input or the result is an empty string it must return false.
SOLUTION
方法一:普通循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functiongenerateHashtag(str) { // 判断是否是空字符串,或只包含多个空格的字符串 if (str.length === 0 || str.replace(/\s+/g, "").length === 0) { returnfalse; } // 将每个单词的首字母大写 let words = str.split(" "); for (let i = 0; i < words.length; i++) { words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); } // 拼接 # let result = "#" + words.join(""); return result.length > 140 ? false : result; }
方法二:reduce() 方法
1 2 3 4 5 6 7
functiongenerateHashtag(str) { var hashtag = str.split(" ").reduce(function (tag, word) { return tag + word.charAt(0).toUpperCase() + word.substring(1); }, "#");