'Error Cannot read property 'toUpperCase' of undefined
Having an array with strings, if a string starts with a letter I want to capitalize the letter, that's all. I'm getting Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase'). That's strange because the function map "sees" all values inside array which are well defined! So why the error?
function camelize(str){
let arr = str.toLowerCase().split(/[^A-Za-z0-9]/g);
let arr2 = arr.map(e => {
if(/[a-z]/.test(e[0])) {
return e[0].toUpperCase() + e.slice(1);
}
else {
return e;
}
});
return arr2.join('').replace(/[^A-Za-z0-9]/g, '');
}
camelize('#hello4&- john');
VM19168:5 Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
at <anonymous>:5:16
at Array.map (<anonymous>)
at camelize (<anonymous>:3:17)
at <anonymous>:1:1
Solution 1:[1]
let arr = '#hello4&- john'.toLowerCase().split(/[^A-Za-z0-9]/g);
console.log(arr)
console.log(arr[0])
console.log(arr[0][0])
Here is the problem:
The first element of an empty string is undefined.
You should filter out the empty strings before calling map.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rsworktech |
