Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting upper and lower case characters in a string

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.

like image 573
James Avatar asked Oct 04 '13 00:10

James


1 Answers

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

like image 129
MrJ Avatar answered Oct 24 '22 19:10

MrJ