0

I am making a character counter as a hobby code. So far, it is working, but I have a glitch I can't seem to solve. When I write the terms "a,b,c", then it correctly writes a:1 b:1 c:1. But when I write "a,a,c,c", then it only writes a:2. I am not sure what's wrong. Here is the JavaScript portion of my code (myFunction is activated by a button, and testinput.value is the value of the textbox I am using):

function myFunction() {
  var occurence = document.getElementById("testinput").value;
  var cycleOne = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
    "u", "v", "w", "x", "y", "z"
  ];
  for (i = 0; i < 26; i++) {
    var counter = new RegExp(cycleOne[i], 'g');
    document.write(occurence.match(counter).length);
  }
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Mister_Maybe
  • 137
  • 1
  • 1
  • 14
  • Is the document closed when this runs? `document.write` blows away closed documents and creates a new blank open one in the same origin. – Mike Samuel Jan 18 '16 at 14:38
  • [`document.write`](https://developer.mozilla.org/en-US/docs/Web/API/document.write) is not purposed to add content to a page in an event handler (i.e after the page has been parsed). Please use a proper DOM manipulation method instead. – Teemu Jan 18 '16 at 14:39
  • For example, `document.body.appendChild(document.createTextNode(occurrence.match(counter).length));` is DOM manipulation of the kind Teemu suggests. – Mike Samuel Jan 18 '16 at 14:40
  • Why don't you check this: [Count the number of occurences of a character in a string in javascript](http://stackoverflow.com/questions/881085/count-the-number-of-occurences-of-a-character-in-a-string-in-javascript) Seems to answer your question perfectly As a side note interestingly enough using RegEx is not actually the fastest way of determining the number of chars in a string but rather using string split (again taken from the answer I cited above) – Pascal Roessner Jan 18 '16 at 14:42

1 Answers1

8

It is printing only 2 because, it is failing with an error, immediately after that.

Let's consider the case when the input is a,a,c,c.

In the first iteration of the loop, you will be matching against a and then it finds two matches and it prints it.

In the second iteration, you will be matching against b and it is not there in the string. So occurence.match(counter) will be returning null and you are trying to get the length property from null. That is why it is throwing the error

TypeError: Cannot read property 'length' of null

and stops execution.


To fix this, you need to check if it is not null, before proceeding, like this

  var result = occurence.match(new RegExp(cycleOne[i], 'g'));
  if (result !== null) {
    console.log(result.length);    
  }
thefourtheye
  • 233,700
  • 52
  • 457
  • 497