Search code examples
javascriptpalindrome

Palindrome issue with JavaScript


I need to write a code with a function that has a parameter str that evaluates if the word is a palindrome or not, it should return true, else ir should return false.

Note: I need to remove all non-alphanumeric characters.

I wrote the code below but it is giving the opposite of the result expected:

  • It is giving false for all the cases.
  • Not able to remove the underscore.
  • and when use console.log below the image I get.

console.log result

Code:

function palindrome(str) {
  var exc = /[^\w_]/gi;
  var repStr = str.toLowerCase().replace(exc, "");
  console.log("Replaced string id: " + repStr);
  len = repStr.length -1

  for (var i = 0; i <= len; i++) {
    if (str[i] !== repStr[len] - i) {
      return false;
    }
  }
  return true;
}

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"));

Solution

  • There are 2 mistakes in your code. 1) the RegExp is not replacing the underscore as [^\w_] reads as "everything that is not a word character OR an underscore". Try

    /[\W_]/g
    

    which reads as "one of the following: any character that is not a word character, underscores"

    OR

    /[^0-9a-z]/g
    

    which reads as "anything that is not: digits (from 0 to 9), english alphabet letters".

    2) For it to work you need to write

    if(repStr[i] !== repStr[len - i])
    

    instead of

    if(str[i] !== repStr[len] - i)