function myReplace(str, before, after) {
let index=str.indexOf(before)
if(str[index]===str[index].toUpperCase()){
after=after.charAt(0).toUpperCase()+after.slice(1)
}
console.log(after)
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
The output shows typeError TypeError: Cannot read properties of undefined (reading ‘toUpperCase’)
What this error is saying is, “We are trying read a property/method called ‘toUpperCase’ but the place we are looking is a variable that evaluates to ‘undefined’. That is illegal.”
That means that either str[index] is undefined or after.charAt(0) is.
I would put in some log statements like this:
function myReplace(str, before, after) {
let index=str.indexOf(before)
console.log('index', index)
console.log('str[index]', str[index])
console.log('after.charAt(0)', after.charAt(0))
if(str[index]===str[index].toUpperCase()){
after=after.charAt(0).toUpperCase()+after.slice(1)
}
console.log(after)
}
myReplace("A quick brown fox umped over the lazy dog", "jumped", "leaped");
This is what @colinthornton was talking about. If I correct the text, I don’t get the error.
And please don’t make changes to code after they’ve been discussed - it makes it confusing to follow the thread.