skip to Main Content

I am trying to create a palindrome checker in Javascript (freeCodeCamp certification project) but keep getting a type error in the "original" var which means the function doesn’t work. I’m not sure what I have missed.

function palindrome(input) {
  var original = input.toLowerCase.replace(/[W_]/gi, '');
  var test = input.toLowerCase.replace(/[W_]/gi, '')
    .split('')
    .reverse()
    .join('');
    
  if (original === test) {
    var result = `${input} is a palindrome.`
  } else {
    var result = `${input} is not a palindrome.`
  }
}

I have tried swapping around const, let and var. I have also changed the order of .toLowerCase and .replace. I don’t know where to go next.

2

Answers


  1. You should call the toLowerCase function with ():

    function palindrome(input) {
      var original = input.toLowerCase().replace(/[W_]/gi, '');
      var test = input.toLowerCase().replace(/[W_]/gi, '')
        .split('')
        .reverse()
        .join('');
        
      if (original === test) {
        var result = `${input} is a palindrome.`
      } else {
        var result = `${input} is not a palindrome.`
      }
      return result
    }
    
    console.log(palindrome('asdfdsa'));
    Login or Signup to reply.
  2. The issue in your code is that you’re not correctly calling the toLowerCase() and replace() functions. The code properly invokes the toLowerCase() and replace() functions as methods on the input string by adding parentheses after each function.

    function palindrome(input) {
      var original = input.toLowerCase().replace(/[W_]/gi, '');
      var test = input.toLowerCase().replace(/[W_]/gi, '')
        .split('')
        .reverse()
        .join('');
        
      if (original === test) {
        var result = `${input} is a palindrome.`;
      } else {
        var result = `${input} is not a palindrome.`;
      }
      return result; // don't forget to return the result
    }
    console.log(palindrome("A man, a plan, a canal, Panama")); // Output: "A man, a plan, a canal, Panama is a palindrome."
    console.log(palindrome("notapalindrome")); // Output: "notapalindrome is not a palindrome."
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search