14

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 things with it:

count letters, count upper and lower case letters, count words and count spaces. Here is what I've done:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Case Check</title>
    <script type="text/javascript">
        function checkCase(text)
        {   

            var counter = 0;
            var letters = 0;
            var lowercase = 0;
            var uppercase = 0;
            var spaces = 0;
            var words = 0;


            for(; counter < text.length; counter++)
            {
                if(isUpperCase(text.charAt(counter))) {uppercase ++; letters++;}
                if(isLowerCase(text.charAt(counter))) {lowercase ++; letters++;} 
                if((text.charAt(counter) == " ") && (counter < text.length))
                {
                    spaces += 1;
                    words += 1;
                }
                if((text.charAt(counter) == ".") || (text.charAt(text(counter)) == ",")) continue;
            }
            return  [letters, lowercase, uppercase, spaces, words];
        }

        function isUpperCase(character)
        {
            if(character == character.toUpperCase) return true;
            else return false;
        }

        function isLowerCase(character)
        {
            if(character == character.toLowerCase) return true;
            else return false;
        }
    </script>
</head>
<body>
    <script type="text/javascript">
        var typed = prompt("Enter some words.");
        var result = checkCase(typed);
        document.write("Number of letters: " + result[0] + "br /");
        document.write("Number of lowercase letters: " + result[1] + "br /");
        document.write("Number of uppercase letters: " + result[2] + "br /");
        document.write("Number of spaces: " + result[3] + "br /");
        document.write("Number of words: " + result[4] + "br /");
    </script>
</body>

Made several changes due to users' suggestions. The problem now is that it won't let me treat 'text' like a string object.

4

7 回答 7

23

使用正则表达式。

例子

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

// numUpper = 2

JavaScript 替换/正则表达式中查看更多信息

于 2014-04-18T20:12:14.280 回答
10

您可以使用 match() 和正则表达式。

var str = "aBcD"; 
var numUpper = (str.match(/[A-Z]/g) || []).length;    // 2
于 2017-06-11T11:55:21.707 回答
2

不确定是否是整个问题,但这个问题很糟糕

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

应该

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

实际上我会成功的

if((text.charAt(letters) == " ") && (text(letters) < text.length))
于 2013-10-04T00:33:27.627 回答
2

isUpperCase并且isLowerCase不是 JavaScript 函数。

你可以用类似的东西替换它们

var isUpperCase = function(letter) {
    return letter === letter.toUpperCase();
};

var isLowerCase = function(letter) {
    return letter === letter.toLowerCase();
};

您的代码中有很多语法错误需要检查。

我也对你所有的括号感到困惑,所以我没有使用charAt我只是像数组一样引用字符串。因此, text.charAt(letters) 我没有使用 text[letters] 我发现更易于阅读的内容。

在此处查看完整的 jsFiddle 。我稍微修改了您的代码,因为 jsFiddle 不允许document.write

于 2013-10-04T01:18:56.190 回答
2

使用 CharCodeAt() 方法的另一种解决方案。

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.'))
于 2020-03-15T20:46:01.797 回答
1

另一种解决方案是使用Array.from()创建一个包含每个字符的数组,str然后使用reduce()它来计算大写字母的数量。

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

console.log(res);

于 2020-03-15T20:28:49.383 回答
0

当字符串包含 UTF8 或变音字符时,这里的大多数解决方案都会失败。可以在 turbocommons 库中找到适用于所有字符串的改进版本,这里:

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

例子:

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

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

更多信息在这里:

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

在这里在线玩它:

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

于 2019-10-16T17:02:28.363 回答