I’m working on my palindrome checker project, and I’ve tested what code I know how to. I think I’m running into an issue with gathering the user input. I think it’s coming out as undefined, and I’m not sure what’s going on. I’m not sure how to add my code either. I’ve been trying to post a topic from the project page, but it keeps not posting. Please help!
const textInput = document.getElementById("text-input");
const checkButton = document.getElementById("check-btn");
const result = document.getElementById("result");
let userInput;
checkButton.addEventListener("click", () => {
userInput = textInput.value;
// 4. When no value is entered...
if (userInput == false) {
alert("Please input a value");
}
// code to run when checking for palindrome
else {
const regex = /[^a-zA-Z0-9]/g;
const stripped = userInput.replace(regex, "").toLowerCase();
if (stripped === stripped.split.reverse.join) {
result.innerText = `${userInput} is a palindrome`;
} else {
result.innerText = `${userInput} is not a palindrome`;
}
console.log(userInput.replace(regex, ""));
}
})
Have you never used copy and paste before? I would Google “how to copy-paste text”. (If that wasn’t what you meant, please clarify and I’ll try to answer!)
I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
const textInput = document.getElementById("text-input");
const checkButton = document.getElementById("check-btn");
const result = document.getElementById("result");
let userInput;
checkButton.addEventListener("click", () => {
userInput = textInput.value;
// 4. When no value is entered...
if (userInput == false) {
alert("Please input a value");
}
// code to run when checking for palindrome
else {
const regex = /[^a-zA-Z0-9]/g;
const stripped = userInput.replace(regex, "").toLowerCase();
if (stripped === stripped.split().reverse().join()) {
result.innerText = `${userInput} is a palindrome`;
} else {
result.innerText = `${userInput} is not a palindrome`;
}
console.log(userInput.replace(regex, ""));
}
})
I was using a console.log to check the values, but I’m not seeing the issue anymore. Yeah, I noticed that the value was undefined outside the function. Interesting observation. I appreciate your help. While I don’t have a working solution yet, I no longer feel stuck, so I’ll keep working on it on my own from here. Thanks!