Home > Software engineering >  SOLVED...I just wonder what is the difference between these two blocks of texts
SOLVED...I just wonder what is the difference between these two blocks of texts

Time:03-16

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");

CodePudding user response:

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");

CodePudding user response:

In the first case, the index is -1 since the string "jumped" is not part of the str --> so str[index] is basically "undefined" and you can not call toUpperCase() with undefined.

in the seconds case, the index is 18 and str[index] is "j" so you can call toUpperCase() since it's a char

CodePudding user response:

You have a typo in your input! Both functions are the same. But in your first implementation you have "jump" in your phrase and you are searching for "jumped" which will end up as error.

this implementation:

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

will always work

  • Related