去除字符串内所有空格【在CodeWars中实践】The Hashtag Generator
参考:https://www.cnblogs.com/a-cat/p/8872498.html
去除字符串内所有的空格:str = str.replace(/\s*/g,"");
去除字符串内两头的空格:str = str.replace(/^\s*|\s*$/g,""); 或者 str.trim();
去除字符串内左侧的空格:str = str.replace(/^\s*/,"");
去除字符串内右侧的空格:str = str.replace(/(\s*$)/g,"");
题目:(https://www.codewars.com/kata/52449b062fb80683ec000024/train/javascript)
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
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata" " Hello World " => "#HelloWorld" "" => false
排在最前的大佬的解答:
function generateHashtag (str) { return str.length > 140 || str === '' ? false : '#' + str.split(' ').map(capitalize).join(''); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }