Javascript Function to Detect Capital String
- 时间:2020-09-07 13:13:13
- 分类:网络文摘
- 阅读:103 次
Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like “USA”.
All letters in this word are not capitals, like “leetcode”.
Only the first letter in this word is capital, like “Google”.
Otherwise, we define that this word doesn’t use capitals in a right way.Example 1:
Input: “USA”
Output: TrueExample 2:
Input: “FlaG”
Output: FalseNote: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
Detect Capital String using Javascript Function
One intutive way is to count the number of Captial letters in the given string. Then it is a valid capital string if: the count is zero (no captial letters), or count is equal to the length (all are captial letters), or count is one and the first character is uppercase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /** * @param {string} word * @return {boolean} */ var detectCapitalUse = function(word) { const len = word.length; if (len === 0) return false; let cnt = 0; let first = false; for (let i = 0; i < len; ++ i) { const ch = word.charAt(i); if ((ch >= 'A') && (ch <= 'Z')) { cnt ++; if (i == 0) first = true; } } return (cnt === 0) || ((cnt === 1) && first) || (cnt === len); }; |
/** * @param {string} word * @return {boolean} */ var detectCapitalUse = function(word) { const len = word.length; if (len === 0) return false; let cnt = 0; let first = false; for (let i = 0; i < len; ++ i) { const ch = word.charAt(i); if ((ch >= 'A') && (ch <= 'Z')) { cnt ++; if (i == 0) first = true; } } return (cnt === 0) || ((cnt === 1) && first) || (cnt === len); };
Using RegExp to Detect Capital String
Using Regular Expression in Javascript helps to make the solution one-line and concise:
1 2 3 4 5 6 7 | /** * @param {string} word * @return {boolean} */ var detectCapitalUse = function(word) { return /^([A-Z]+|[A-Z][a-z]*|[a-z]+)$/.test(word); }; |
/** * @param {string} word * @return {boolean} */ var detectCapitalUse = function(word) { return /^([A-Z]+|[A-Z][a-z]*|[a-z]+)$/.test(word); };
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:此菜肴脆嫩爽口肉香浓郁且色香味俱全,为冬季百吃不厌的佳肴 枸杞子吃法正确才能更好吸收营养,但人在出现状况时最好别吃它 土豆是一种非常普通的蔬菜,但其营养保健价值令人难以置信 大家别忘了喝碗营养丰富的腊八粥,它对女性朋友的好处尤其多 经常吃一点柚子好处多,柚子皮的作用也不少,以后别再浪费啦 牛奶是常见的营养饮品,如果选择不对,既浪费钱还影响健康 香蕉对身体健康有很多好处,教你用香蕉做一道美味粥吧 香菇与洋葱搭配在一起营养全面,使得保健功效会更好 分数的运算古代的分数除法 巧用份数解决问题
- 评论列表
-
- 添加评论