I want to calculate how many times characters appear in a text, and then display the totals for each character. My main problem is the first part.
Here is a snapshot of my code so far:
//define text and characters to be searched for
var theArticle = document.getElementById('theText'),
docFrag = document.createDocumentFragment(),
theText = theArticle.innerText,
characters = {
a: {
regExp: /a/g,
matches: [],
count: 0
},
b: {
regExp: /b/g,
matches: [],
count: 0
},
c: {
regExp: /c/g,
matches: [],
count: 0
}
etc…
}
for (var key in characters) {
if (characters.hasOwnProperty(key)) {
var obj = characters.key;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
matches = theText.match(regExp); // pretty sure my problem is here
count = matches.length; // and here
}
}
}
}
I would like to loop through all the characters to set the value of matches
based on regExp
and the value of count
based on the length of matches
.
The top answer to this question is the closest I've come to solving my problem. Access / process (nested) objects, arrays or JSON