I have a string from input that I need to transform to CAP on each first word using keyup.
here is the script:
$(".cap_first").on("keyup", function () {
const string = $(this).val();
const words = string.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1).toLowerCase();
}
$(this).val(words.join(" "));
});
It return as what I need and work but on console show me this error: "Uncaught TypeError: words[i][0] is undefined"
I understand a rule that if it work, then don't touch. But I feel something wrong if the console show an red
Thanks
I have tried to change the const name but still show the error
Most cases something like
Uncaught TypeError: words[i][0] is undefinedis caused when words[i] is of size 0, i.e. empty string.In your case if the user enters a a string with two consecutive whitespace, the split array will have one item of length 0. And since the length is zero you will get the above error when trying to access index 0.