Hi. I am coding the palindrome project and at the end I get error:
[TypeError: Cannot read properties of undefined (reading ‘trim’)]
even though I am not using trim method anywhere. There error only occurs when I run the tests. Else the program works just fine, no errors.
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Palidrome checker</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Is it a palindrome?</h1>
<container>
<h3>Enter in text to check for a palindrome:</h2>
<div id="inputDiv">
<input id="text-input">
<button id="check-btn">Check</button>
<div>
<div id="result">
</div>
</container>
<script src="script.js"></script>
</body>
</html>
Javascript:
const inputBox = document.getElementById("text-input");
const checkBtn = document.getElementById("check-btn");
const resultDiv = document.getElementById("result");
checkBtn.addEventListener("click", () => {
let userInput = inputBox.value;
CheckIfPalindrome(userInput);
});
function CheckIfPalindrome(str) {
if (str == "") {
resultDiv.textContent = "Please input a value";
}
else {
let trimmedStr = removeSpecialChars(str).replace(" ", "");
let reversedStr = "";
for (let i = trimmedStr.length - 1; i >= 0; i--) {
reversedStr += trimmedStr.charAt(i);
}
let result = `${str} ${trimmedStr === reversedStr ? "is a palindrome" : "is not a palindrome"}`
resultDiv.textContent = result;
}
}
function removeSpecialChars(str) {
let newStr = "";
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if ((charCode >= 65 && charCode <= 90) ||
(charCode >= 97 && charCode <= 122) ||
(charCode >= 48 && charCode <= 57))
{
newStr += str[i];
}
}
return newStr;
}