Search code examples
javascripttypeerrorvariadic-functionsstring-length

Cannot read property 'length' of null, javascript. Check if given string contain letters: p & t


Im trying debug my JS mini projects. A few of them, shows:

Uncaught TypeError: Cannot read property 'length' of null at task(xx)

Those mini-projects works, but I would like to delete all the bugs.

This task is about: check whether a given string contains equal number of p's and t's.

I followed message of the bug, as I understand if the length of variable is null or 0, that means this is undefined and cannot be validated. So, unsuccesfully, I tried use this piece of code:

if (p < 0 || t< 0) 
or 
if (task55word == null)

The basic code is here:

task55 = () => {
  const task55word = document.getElementById("task55").value;
  const task55ans = document.getElementById("task55ans")
  const wordP = task55word.toLowerCase().match(/p/g);
  const wordT = task55word.toLowerCase().match(/t/g);
  const p = wordP.length;
  const t = wordT.length;
  if (p == t) {
 task55ans.textContent = 'equal';
  } else {
    task55ans.textContent = 'not equal';
  }
};

What I have done wrong?


Solution

  • Try this code. match returns null if nothing matches.

    task55 = () => {
      const task55word = document.getElementById("task55").value;
      const task55ans = document.getElementById("task55ans");
      const wordP = task55word.toLowerCase().match(/p/g) || "";
      const wordT = task55word.toLowerCase().match(/t/g) || "";
      const p = wordP.length;
      const t = wordT.length;
      if (p == t) {
        task55ans.textContent = 'equal';
      } else {
        task55ans.textContent = 'not equal';
      }
    };