Error message on looping "for" javascript

89 Views Asked by At

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

2

There are 2 best solutions below

1
Niki On

Most cases something like Uncaught TypeError: words[i][0] is undefined is 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.

let str = "2  spaces";
let words = str.split(" ");  // ['2', '', 'spaces']
1
Anil kumar On

Why work manually when you have css for this job.

/*p {text-transform: capitalize;}*/
 p {
            text-transform: lowercase;
        }
   
    p::first-letter {
            text-transform: uppercase;
        }
<p>error message on Looping "for" Javascript</p>