Palindrome Checker

function palindrome(str) {

// remove all non-alphanumeric characters 
// turn everything into the same case in order
const replacedStr = str.replace(/[^a-z0-9]/gi, '');
// create reversed version of str
let reverseString = str.split("").reverse().join("");

for (let i = 0; i < replacedStr.length; i++) {
  if (replacedStr === reverseString) return true;
}
  return false;
} 


console.log(palindrome("eye"));

I really thought this would work. The problem seems fairly straightforward but I guess not. I know the last 5 problems are supposed to hint free, so can someone give me a little help without giving anything away? Thanks

I would console.log both replacedStr and reverseString.

2 Likes
function palindrome(str) {

// remove all non-alphanumeric characters 
// turn everything into the same case in order

const replacedStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
console.log(replacedStr)
// create reversed version of str
let reverseString = str.replace(/[^a-z0-9]/gi, '').toLowerCase().split("").reverse().join("");
console.log(reverseString)

for (let i = 0; i < replacedStr.length; i++) {
  if (replacedStr === reverseString) return true;
}
  return false;
} 

console.log(palindrome("A man, a plan, a canal. Panama"));

Got it, thank you so much for the small pointer! Feels nice getting through these problems on my own, no better feeling

In terms of improvements, take a closer look at this part:

for (let i = 0; i < replacedStr.length; i++) {
  if (replacedStr === reverseString) return true;
}
  return false;
} 

What is the loop doing?

1 Like

Very true, I noticed that after I added it to this thread but just didn’t change it. But yeah the for loop is completely unnecessary. This works perfectly fine:

function palindrome(str) {

// remove all non-alphanumeric characters 
// turn everything into the same case in order

const replacedStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
console.log(replacedStr)
// create reversed version of str
let reverseString = str.replace(/[^a-z0-9]/gi, '').toLowerCase().split("").reverse().join("");
console.log(reverseString)


  if (replacedStr === reverseString) { 
  return true;
}
  return false;
} 

palindrome("eye");

This evaluates to a boolean, so you don’t even need an if statement.

return replacedStr === reverseString
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.