Actualmente estoy aprendiendo JavaScript en FreeCodeCamp y tengo que hacer un comprobador de palíndromo. Traté de escribir mi propio código para hacerlo, la mayoría de las pruebas de verificación necesarias para la validación devuelven la respuesta correcta y esperada. Pero tres de las pruebas de verificación no son buenas. He estado buscando por qué, pero no puedo resolverlo.
En este ejercicio, tengo que aislar los caracteres no alfanuméricos de la cadena y verificar si la cadena es un palíndromo sin ellos.
Valores incorrectos:
str = "_eye" (should return true) str = "almostomla" (should return false) str = "My age is 0, 0 si ega ym." (should return true)Mi código en este momento:
function palindrome(str) { const nonAlpha = /^[^a-zA-Z0-9]+$/gi; str.replace(nonAlpha, ""); // replacing non alphanumerics characters with a regex const lowerCaseString = str.toLowerCase(); // converting string to lower case let strMaxIndex = str.length - 1; // checking what is the max index of str let startIndex = 0; while (startIndex !== strMaxIndex) { if (lowerCaseString[startIndex] === lowerCaseString[strMaxIndex]) { // checking if characters from the left are the same from the right startIndex += 1; // going from left to center of str strMaxIndex -= 1; // going from right to center of str return true; } else if (lowerCaseString.length <= 2) { // can't be a palindrome if it has only 2 characters return false; } else { return false; } } } palindrome("eye");