Counting upper and lower case characters in a string

后端 未结 7 558
礼貌的吻别
礼貌的吻别 2020-12-19 03:25

First off, I know this is far from professional. I\'m trying to learn how to work with strings. What this app is supposed to do is take a simple text input and do a few thi

相关标签:
7条回答
  • 2020-12-19 04:04

    Not sure if whole problem, but bad paren on this one

    if(text.charAt(letters)) == " " && text(letters) < text.length)
                           ^
    

    Should be

    if(text.charAt(letters) == " ") && text(letters) < text.length)
                                  ^
    

    And actually I'd make it

    if((text.charAt(letters) == " ") && (text(letters) < text.length))
    
    0 讨论(0)
  • 2020-12-19 04:09

    Use regular expressions.

    Example

    var s = "thisIsAstring";
    var numUpper = s.length - s.replace(/[A-Z]/g, '').length;  
    
    // numUpper = 2
    

    Se more at JavaScript replace/regex

    0 讨论(0)
  • 2020-12-19 04:16

    Another solution using CharCodeAt() method.

    const bigLettersCount = (str) => {
      let result = 0;
      for (let i = 0; i < str.length; i += 1) {
        if (str.charCodeAt(i) > 64 && str.charCodeAt(i) <91 ) {
          result += 1;
        }
       }
       return result
      }
    
    console.log(bigLettersCount('Enter some words.'))
    
    0 讨论(0)
  • 2020-12-19 04:16

    Most of the solutions here will fail when string contains UTF8 or diacritic characters. An improved version that works with all strings can be found at the turbocommons library, here:

    https://github.com/edertone/TurboCommons/blob/1e230446593b13a272b1d6a2903741598bb11bf2/TurboCommons-Php/src/main/php/utils/StringUtils.php#L391

    Example:

    // Returns 2
    StringUtils.countByCase('1声A字43B45-_*[]', StringUtils.FORMAT_ALL_UPPER_CASE);
    
    // Returns 1
    StringUtils.countByCase('1声A字43B45a-_*[]', StringUtils.FORMAT_ALL_LOWER_CASE);
    

    More info here:

    https://turbocommons.org/en/blog/2019-10-15/count-capital-letters-in-string-javascript-typescript-php

    Play with it online here:

    https://turbocommons.org/en/app/stringutils/count-capital-letters

    0 讨论(0)
  • 2020-12-19 04:16

    Another solution is using Array.from() make an array which includes each character of str and then using reduce() to count the number of the uppercase letters.

    const str = 'HeLlO';
    const res = Array.from(str).reduce((acc, char) => {  
      return acc += char.toUpperCase() === char;
    }, 0);
    
    console.log(res);

    0 讨论(0)
  • 2020-12-19 04:17

    You can use match() and regular expressions.

    var str = "aBcD"; 
    var numUpper = (str.match(/[A-Z]/g) || []).length;    // 2
    
    0 讨论(0)
提交回复
热议问题