Search code examples
javascriptindexofuppercase

What is the difference between these two blocks of texts


The first function doesn't work. It shows the message "Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'toUpperCase')"

These are the codes:

//this is the one with error
function myReplace(str, before, after){
    var index = str.indexOf(before);
    if (str[index] === str[index].toUpperCase()) {
        after = after.charAt(0).toUpperCase()+ after.slice(1);
    }else{
        after = after.charAt(0).toLowerCase() + after.slice(1);

    }
    str = str.replace(before, after);
    return str;
    }

myReplace("A quick brown fox jump over the lazy dog", "jumped", "leaped");


//This apparently works fine.
function myReplace(str, before, after){
    var index = str.indexOf(before);
    if (str[index] === str[index].toUpperCase()) {
        after = after.charAt(0).toUpperCase()+ after.slice(1);
    }else{
        after = after.charAt(0).toLowerCase() + after.slice(1);

    }
    str = str.replace(before, after);
    return str;
    }
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

Solution

  • The code is semantically incorret. In the first example you never use the word "jumped" instead you use "jump". Therefore the result of the indexOf function cant be used. See the following snippet to further understand what's wrong. If the indexOf function can not find the substring, it will return a -1.

    Since you can not access -1 in an array it will return the seen error. You should always handle these edge cases in your code to avoid unwanted behaviour. I added a check of the index before trying to access something.

    //this is the one with error
    function myReplace(str, before, after){
        var index = str.indexOf(before);
        console.log(index);
        if(index < 0){
          return "error index not found"
        }
        if (str[index] === str[index].toUpperCase()) {
            after = after.charAt(0).toUpperCase()+ after.slice(1);
        }else{
            after = after.charAt(0).toLowerCase() + after.slice(1);
    
        }
        str = str.replace(before, after);
        return str;
        }
    
    myReplace("A quick brown fox jump over the lazy dog", "jumped", "leaped");