0

After 3 days of not being able to complete this challenge, I ended up finding another solution.

Nonetheless, I'm curious as to why my code is always returning true for all results instead of false for some results:

function palindrome(str) {

  // CONVERT TO ALL LOWER CASE
  str = str.toLowerCase();

  // REMOVE ALL NON-ALPHANUMERIC CHARACTERS (PUNCTUATION, SPACES AND SYMBOLS)
  // Loop through string and push each character in an array
  let strArr = [];
  for (let i = 0; i < str.length; i++) {
    strArr.push(str[i])
    // Remove non-alphanumeric characters
    if (str[i] === /[^0-9a-z]/gi) {
        strArr.splice(str[i], 1);
    }
  }

  // CHECK IF STRING IS IDENTICAL FORWARDS AND BACKWARDS
  // Create reverse string
  let strArrRev = strArr;
  strArrRev = strArrRev.reverse();
  if (strArr === strArrRev) {
    return true;
  } else {
    return false;
  }
}

console.log(palindrome("eye"));
console.log(palindrome("_eye"));
console.log(palindrome("race car"));
console.log(palindrome("not a palindrome"));
console.log(palindrome("A man, a plan, a canal. Panama"));
console.log(palindrome("never odd or even"));
console.log(palindrome("nope"));
console.log(palindrome("almostomla"));
console.log(palindrome("My age is 0, 0 si ega ym."));
console.log(palindrome("1 eye for of 1 eye."));
console.log(palindrome("0_0 (: /-\ :) 0-0"));
console.log(palindrome("five|\_/|four"));
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Kynan
  • 21
  • 5
  • 1
    `str[i] === /[^0-9a-z]/gi` This doesn't do what you think it does. You cannot compare a string to a regex. When using a regex, you need to use `.match()` or `.replace()`. – gen_Eric Aug 03 '21 at 17:44
  • Also, it's better to match/replace the _whole_ string against the regex, instead of looping and matching each character. – gen_Eric Aug 03 '21 at 17:46

0 Answers0