0

So I am working on a project and am having a bit of an issue. I need to have an HTML page with a Text Area, and I need to on a button click calculate how many of each letter in the alphabet are in the string in said Text Area.

For example in the string:

"The Quick Brown Fox Jumps Over the Lazy Dog"

The results would be:

A = 1, B = 1, C = 1, O = 4, etc.

The easiest way I can think to do this is to convert the contents of the Text Area to an array with each array element being a single character (if I could manage to exclude spaces, that would also be sweet) and then compare that Array, to a second array where each element is a different letter of the alphabet.

My biggest problem is that I have no idea how to do this. As the title says I'm using Javascript for this, and I've tried looking on here, as well as using Google, but am coming up with nothing. Thank you in advance for anyone who offers help :)

Skitzafreak
  • 1,797
  • 7
  • 32
  • 51
  • Start with a web search...this is a common exercise and should be very easy to find lots of examples using javascript string terms – charlietfl Nov 20 '16 at 21:30
  • You would think. But I've been trying to search for a solution to this for an hour. But all I am coming up with is how to make an array where each element is the next line of the text area. Not the next character in the string. – Skitzafreak Nov 20 '16 at 21:38

4 Answers4

1

How about:

var CharOccurrences = {};
for(var i=0; i<sTextContent.length; i++){
    var c = sTextContent.charAt(i);
    if(typeof CharOccurrences[c] == 'number'){
            CharOccurrences[c]++;
    }else{
        CharOccurrences[c] = 1;
    }
}

CharOccurrences would essentially act as a map for each character in the the string and it would contain a count for each time a character occurred.


Alternatively, the following could be used to count ONLY the characters of the alphabet that occur:

var AlphaCharsInText = sTextContent.match(/[a-zA-Z]/g);
var CharOccurrences = {};
for(var i=0; i<AlphaCharsInText.length; i++){
    var c = AlphaCharsInText[i];
    if(typeof CharOccurrences[c] == 'number'){
            CharOccurrences[c]++;
    }else{
        CharOccurrences[c] = 1;
    }
}
Spencer D
  • 3,376
  • 2
  • 27
  • 43
  • 1
    small nitpick (I hate being that guy) - I would charAt() instead of array syntax on the string...just for browser compat stuff. +1 though. – Mike S. Nov 20 '16 at 21:39
  • @MikeS., duly noted. I'll edit to include that ;) – Spencer D Nov 20 '16 at 21:40
  • This is something I haven't really come across before. In Javascript can any String be written as stringVar[index] and return whatever character is at 'index'? – Skitzafreak Nov 20 '16 at 21:42
  • @Skitzafreak, as Mike S. pointed out, for browser compatibility, one should use `string.charAt(number)`, but many browsers do support an array-like index access to get a specific character at a point in a string. However, I would strongly advise using `charAt(#)` as that is the standard method for getting a character at a given position in Javascript. – Spencer D Nov 20 '16 at 21:45
  • 1
    http://stackoverflow.com/questions/5943726/string-charatx-or-stringx – Mike S. Nov 20 '16 at 21:46
  • @MikeS. so I went and typed out your first code block, just to understand it a bit better, and I was getting the error "charAt is not a function" O__o – Skitzafreak Nov 21 '16 at 00:10
  • @Skitzafreak, are you referring to the code in my answer, or the code in the post linked to by Mike? – Spencer D Nov 21 '16 at 03:06
0

There are, of course, many ways to do this. Here's one that roughly follows what I believe you had in mind. If you want to capture all characters, instead of just the alphanumeric ones, you could remove the filter statement.

 function numChars(str) {
    var chars = {};
    str.split('')
        .filter(c => /[a-z]/i.test(c))
        .map(c => c.toLocaleUpperCase())
        .forEach(c => chars[c] = chars[c] + 1 || 1);
    return chars;
}

numChars("The Quick Brown Fox Jumps Over the Lazy Dog");

Or alternatively, this will only really work for a-z.

function numChars(str) {
    var chars = Array(26).fill(0);
    str.split('')
        .map(c => c.toLocaleUpperCase())
        .filter(c => /[A-Z]/.test(c))
        .forEach(c => {
            chars[c.codePointAt(0) - 65]++;
        });
    return chars; //chars[0] = a, chars[1] = b
}

numChars("The Quick Brown Fox Jumps Over the Lazy Dog");
Gerrit0
  • 7,955
  • 3
  • 25
  • 32
0

To access the content of the textarea you would use its value attribute. This results in a string, now you only need to work with it. To split a string into an array of characters you could use the split function, to count each character you would iterate over that array and increment a counter built via an object of the form character: count.

The following JavaScript uses ES6 syntax.

// your textarea element
const ta = document.querySelector('#text')

// create a handy function
const count = textarea => {
    let counts = { }
    textarea.value.toUpperCase()
                  .split('')
                  .sort() // not really needed but creates a nicer lookign output
                  .forEach(x => counts[x] = (counts[x] || 0) + 1)
    return counts
}

console.log(count)

Of course you could also add a filter after the call of the split function to only count letters.

View a demo on https://jsfiddle.net/z46fgnqh/

max-m
  • 847
  • 7
  • 9
0

I just wrote a code for you that uses match to get the number of occurrences of all characters. It is working just as you wanted.

 var text = "The Quick Brown Fox Jumps Over the Lazy Dog"
 var charArray = text.split("");
 var charObject ={};
 for(I=0;I<text.length;I++){
 var txt = charArray[I];
   charObject[txt] = text.match(new RegExp(txt,"gi")).length;
   }
   for(x in charObject){ 
    document.write( x +": "+charObject[x] + "<br>");
    }
Taiti
  • 375
  • 2
  • 6