HELP: Search and Replace Algorithm

Hi, there.
This code works for me locally. When I run it on FCC platform It yells. What’s wrong? THX.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>FCC - Search and Replace</title>
    <h1>FreeCodeCamp - Intermediate Algorithm Scripting</h1>
    <h3>Search and Replace*</h3>
        Perform a search and replace on the sentence using the arguments provided and return the new sentence.
        First argument is the sentence to perform the search and replace on.
        Second argument is the word that you will be replacing (before).
        Third argument is what you will be replacing the second argument with (after).
        NOTE: Preserve the case of the original word when you are replacing it. For example if you mean to 
        replace the word "Book" with the word "dog", it should be replaced as "Dog".
        function myReplace(str, before, after) {
            if(str.indexOf(before) === -1) {
                return str; // "before" is not into "str".
            } else {
                if(str.charCodeAt(str.indexOf(before)) <= 90) {
                    after[0] = after.charAt(0).toUpperCase();
            return str.replace(before, after);

        console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
        console.log(myReplace("Let us go to the store", "store", "mall"));
        console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"));
        console.log(myReplace("This has a spellngi error", "spellngi", "spelling"));
        console.log(myReplace("His name is Tom", "Tom", "john"));
        console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"));
        console.log(myReplace("My name is jose", "jose", "Jose"));
        console.log(myReplace("This is a Test", "Test", "test"));
        console.log(myReplace("This a single string", "code", "Code"));

after is a string. Strings are immutable, you can’t mutate parts of them: after[0] = can’t work. It cannot be working locally, because what you’re trying to do on that line of code is impossible in JS. When the tests run, all the ones that need to retain the case fail because of that.

You need to do something like take the first letter, upper/lowercase it, then concatenate it to the rest of the word to make it work.

Also, minor, but checking the character code range is not an accurate way of determining upper/lowercase. It will allow you to pass the given tests, but they are there as basic examples. What happens with accented characters, so words like “éclair”? Checking the first character is the same as the first character toLowercase or toUppercase is safer

1 Like