The Hashtag Generator

题目

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.

Examples

1
2
3
" Hello there thanks for trying my Kata"  =>  "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false

分析

  • 正则式替换掉多余的空白,\s是空白n{X,}是n至少出现X次时匹配
  • 校验是否为空
  • 字符串分割为数组,首字母大写
  • 组合后判断长度是否超过140个字符

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function generateHashtag (str) {
// 消除多余空格
let nStr = str.replace(/\s{2,}/g, ' ');
if (nStr === ''|| nStr===' ') {
return false;
} else {
let arr = nStr.split(' ')
// 首字母大写
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1).toLowerCase();
}
let newStr = arr.join('');
if (newStr.length > 139) {
return false;
} else {
return '#' + newStr;
}
}
}