Build a Palindrome Checker - Run the Tests

Run the Tests button returns failure on working JavaScript. Below JavaScript works fine on the all test cases. You can test this code on your side.

const textInput = document.getElementById(“text-input”);
const checkBtn = document.getElementById(“check-btn”);
const result = document.getElementById(“result”);

checkBtn.addEventListener(“click”, () => {
let isPalindrome = true;
let alphaNumericString = new String(textInput.value).trim().toLowerCase().replace(/[^a-zA-Z0-9]/g,“”);
if (alphaNumericString.length == 0) {
alert(“Please input a value”);
} else {
for (i = 0; i < alphaNumericString.length / 2; i++) {
if(alphaNumericString[i] != alphaNumericString[alphaNumericString.length - i - 1]) {
isPalindrome = false;
break;
}
}
result.innerText = isPalindrome ? textInput.value + " is a palindrome" : textInput.value + " is not a palindrome";
}
});

Palindrome Test

Enter

body {
background-color: black;
color: white;
}

This is very simple as you see but the ‘Run the Tests’ buttonn fails to test this code.

Welcome to the forum @hsyeon01

Please post your html code as well so the forum can assist.

Happy coding

Hi @hsyeon01

The i variable in the for loop needs to be declared.

Thanks for posting the html code in the correct format.

Happy coding

<!DOCTYPE html>
 <html>
    <head>
        <link rel="stylesheet" href="./styles.css" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Palindrome Test</h1>
        <p>     
            <input type="text" id="text-input">
            <button type="button" id="check-btn">Enter</button>
            <div id="result">            
            </div>
        </p>
        <script src="./script.js"></script>
    </body>
 </html>```

Thanks but why this js works without any error without ‘let’ in for loop?

If you omit declaring a variable you are implicitly creating a global variable.
Good practice is to declare variable scope.

Happy coding

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.