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?
CodePudding user response:
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.
CodePudding user response:
This line causes the error.
string = " " sentences[i][1].toUpperCase() sentences[i].substring(2).toLowerCase() ".";
your split separates the string at a point. if there is nothing after the point, there is also an empty element in the array. and that is why the [0] throws an error. because a lerrer string has no first character. to fix the error, you must first catch this case.
for example
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 {
console.log(sentences[i][1]);
let s1 = ''
let s3 = ''
if(typeof sentences[i][0] !== "undefined") {
s1 = " " sentences[i][0].toUpperCase();
s3 = ".";
}
string = s1 sentences[i].substring(2).toLowerCase() s3;
}
}
console.log(string)
document.querySelector("textarea").value = string;
})