Build a Palindrome Checker Project - Build a Palindrome Checker

Tell us what’s happening:

Describe your issue in detail here.
The problem is that all the user stories work except for the alert if the input value is empty one.
This is the error in the console that I recieve when I check with the button that I made: Uncaught TypeError: Cannot read properties of null (reading ‘reverse’)
And this is the error in the console when I test the whole app:
// running tests When you click on the

#check-btn

element without entering a value into the

#text-input

element, an alert should appear with the text

"Please input a value"

. // tests completed // console output Uncaught TypeError: Cannot read properties of null (reading ‘reverse’) [TypeError: Cannot read properties of undefined (reading ‘trim’)]

Your code so far

<!-- file: index.html -->
<input id="text-input">
<button id="check-btn">check</button>
  <div id = "result"></div>
<script src="script.js"></script>
/* file: styles.css */

/* file: script.js */
const input = document.getElementById("text-input");
const button = document.getElementById("check-btn");
const result = document.getElementById("result");

button.addEventListener("click",palindrome);
function palindrome() {
    const inputVal = input.value.trim();
    const normalStr = inputVal.toLowerCase().match(/[a-z0-9]/g).reverse().join('');
    const reversedStr = inputVal.toLowerCase().match(/[a-z0-9]/g).join('');
    if(inputVal == " ") {
        alert("Please input a value");
    }else if(normalStr === reversedStr) {
        document.querySelector("#result").innerHTML = `${inputVal} is a palindrome`;
    }else if(normalStr !== reversedStr) {
        document.querySelector("#result").innerHTML = `${inputVal} is not a palindrome`;
    }
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 OPR/107.0.0.0

Challenge Information:

Build a Palindrome Checker Project - Build a Palindrome Checker

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

If the inputVal is an empty String "" the normalStr will run the match on the empty String and return null which you can’t use reverse() on that.

So you need to move that condition:

before the normalStr constant but with two little improvements:
First, remove that space between that double quotes, because it’s not an empty string that way. It’s a space literally. it should be like this "".

and after your alert statement, use return to exit the function and stop executing to bypass the issue with normalStr in case of empty String.

And for sure, edit your else if statement to be if cause you will have moved that first if.

Thank you so much for the clear explanation ,that did the trick.

1 Like

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