-1

I am learning JavaScript and I made a function that check if a string is an palindrome or not, that function remove all non-alphanumeric characters and turn everything in lowercase, and I need your help to "simplificate" that code. I didnt liked the part that i turned everythink into an array and the way i check if the letter is alphanumeric or not.

function palindrome(str) {
  str = str.replace(/\s+/g, '');
  str = str.toLowerCase();
  let aux = '';
  let aux2= '';
  let array = [];
  for(let i=0;i<str.length;i++)
    if(str[i] == "!" || str[i] == "@" || str[i] == "#" || str[i] == "$" || str[i] == "%" || str[i] == "&" || str[i] == "*" || str[i] == '\"' || str[i] == "/" || str[i] == "(" || str[i] == ")" || str[i] == ":" || str[i] == ";" || str[i] == "-" || str[i] == "_" || str[i] == "." || str[i] == ","){
    }else{
      aux+=str[i];
    }
  for(let j=0;j<aux.length;j++){
    array.unshift(aux[j]);
  }
  for(let x=0;x<array.length;x++){
    aux2+=array[x];
  }
  if(aux==aux2){
    return true;
  }else{
    return false;
  }
}
  • [palindrome-check-in-javascript](https://stackoverflow.com/questions/14813369/palindrome-check-in-javascript) – Idan Aug 27 '22 at 21:09

1 Answers1

0

You can just reverse the string and check to see if that is the same as the original to check if it's a palindrome.

const validDisplay = document.querySelector(".isValid");
function changeDisplay(valid) {
  if (valid) validDisplay.classList.add("valid");
  else validDisplay.classList.remove("valid");
}

function isPalendrome(str) {
  const validString = str.replace(/[^a-zA-Z]/g, "").toLowerCase();
  const reversedString = [...validString].reverse().join("");
  return validString == reversedString;
}

document.querySelector("input").addEventListener("input", e => {
  const val = e.target.value;
  const isValid = isPalendrome(val);
  changeDisplay(isValid);
});
.isValid {
  width: 50px;
  height: 20px;
  background-color: red;
}

.isValid.valid {
  background-color: green;
}
<input type="text" />
<div class="isValid"></div>
async await
  • 1,967
  • 1
  • 8
  • 19