I am working through the Palindrome checker and having an issue where the if/else block in my code is hitting the else statement when it shouldn’t have. This only seems to occur when I pass in a text value that has a space in it. If I only pass in values without a space it works as expected.
Here is my code so far.
const checkButton = document.getElementById("check-btn");
const inputValue = document.getElementById('text-input');
checkButton.addEventListener('click', event => {
if(inputValue.value === 'input text here'){
alert("please Enter Text!!")
} else {
if(inputValue.value.includes(' ')){
let str = checkForSpaces(inputValue.value)
checkForPalindrom(str);
}
checkForPalindrom(inputValue.value);
}
});
const checkForPalindrom = (input) => {
const textArray = input.split('');
const revArray = [];
while(textArray.length > 0){
let endString = textArray.pop();
revArray.push(endString);
}
let newWord = revArray.join('');
if(input === newWord){
alert('YOU HAVE A PALENDROME!!!')
}else{
alert('You dont have a Palendrome!!')
}
}
const checkForSpaces = (input) => {
const spaceArray = input.split('');
let indexOfFirst = input.indexOf(' ');
spaceArray.splice(indexOfFirst,1);
let newSTR = spaceArray.join('');
return newSTR;
}
What I thought should happen was when you pass a value that has a space the checkForSpaces function would get executed first. This would remove the space and return a string without space. Which then would pass the new string value to my checkForPalindrom function with out the space where it reverses the string and checks if its the same as original value. There for it should only fall into the else block if the value you have is not a palindrome. However it seems to be executing both the if block and then the else block for values that contained a space.
I’m lost.