Search code examples
javascripttypeerroruppercase

Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')


I have been trying to convert the text input to proper case and sentence case. Proper case seems to work fine but the sentence case throws Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase'). Went through this post and applied few changes but found no luck. Surprisingly, the .toUpperCase() works just fine in the proper case function.

document.getElementById("proper-case").addEventListener("click", function() {
  let words = document.querySelector("textarea").value.split(" ");
  let string = "";
  for (let i = 0; i < words.length; i++) {
    string += words[i][0].toUpperCase() + words[i].substring(1).toLowerCase();
    if (i != words.length - 1) {
      string += " ";
    }
  }
  document.querySelector("textarea").value = string;
});


document.getElementById("sentence-case").addEventListener("click", function() {
  let sentences = document.querySelector("textarea").value.split(".");
  let string = "";
  console.log(sentences);
  for (let i = 0; i <= sentences.length - 1; i++) {
    if (i == 0) {
      string += sentences[i][0].toUpperCase() + sentences[i].substring(1).toLowerCase() + ".";
    } else {
      string += " " + sentences[i][1].toUpperCase() + sentences[i].substring(2).toLowerCase() + ".";
    }
  }
  console.log(string)
  document.querySelector("textarea").value = string;
})
<textarea></textarea>

<button id="proper-case">Proper Case</button>
<button id="sentence-case">Sentence Case</button>

Can someone please tell me what the problem here is?


Solution

  • The .split('.') operation returns an empty string at its last array item, therefore, sentences[i][1] is undefined. To solve this, you can check if sentences[i] is not an empty string.

    In addition, you can use String.trimLeft() on the else case.