I built a site where you can convert your text to, for example, Title Case. It works, but there is a small problem. When the textarea is empty, and I click on the button which is there to convert the text to Title Case, following error is thrown: TypeError: Cannot read properties of undefined (reading 'toUpperCase').

I already checked if "el" is a string, even when it is empty, and it is, but I dont understand why I still get the error. I know that you can't call toUpperCase on null, undefined etc., but apparently "el" is none of that, even when the textarea is empty.

Here is part of the code:

titleCase.addEventListener("click", function () {
  const exceptions = [
    "a",
    "and",
    "as",
    "but",
    "by",
    "down",
    "for",
    "from",
    "if",
    "in",
    "into",
    "like",
    "near",
    "nor",
    "of",
    "off",
    "on",
    "once",
    "onto",
    "or",
    "over",
    "past",
    "so",
    "than",
    "that",
    "to",
    "upon",
    "when",
    "with",
    "yet",
  ];
  const transformation = textArea.value
    .toLowerCase()
    .split(" ")
    .map((el) =>
      exceptions.includes(el) ? el : el[0].toUpperCase() + el.slice(1)
    )
    .join(" ");
  textArea.value = transformation[0].toUpperCase() + transformation.slice(1);
});
0

There are 0 best solutions below