Palindrome-checker, which one is best?

Here is my original code:

function palindrome(str) {
	// \W matches any non-word character = [^a-zA-Z0-9_] 
	var symbols = /\W|_/g;

	// replace symbols with empty value = string excludes all those symbols
	str = str.replace (symbols, "").toLowerCase();
	//console.log("str = " +str);
	var palindromic = str.replace(symbols,"")
	.toLowerCase()
	.split("")
	.reverse("")
	.join("");

  return Boolean(str === palindromic);

But I also found these two solutions to the problem:

function palindrome(str) {
  var replaced ="";
  var string =""; // string without symbols to compare with backwarded string
  replaced=str.toLowerCase().replace(/\W|_/g,"").split("").reverse().join("");
  string =str.toLowerCase().replace(/\W|_/g,"");
  
  if (replaced == string) {
    return true;
    
  }
  else
 return false;
}

And

function palindrome(str) {

  str = str.replace(/[\W_]/gi, "").toLowerCase();
  return str === str.split("").reverse().join("")

}

Obviously the shorter one is probably preferred since it looks cleaner, but in your opinion, is the short one the best overall? Were there redundancies in my code or unnecessary stuff?

This was really my first exposure to .split, .reverse, .join etc. I kind of just jumped into the project so a lot of it was trial and error for me, and youtubez.

Cheers!

1 Like

Hi frtb0x,

Using

return str === palindromic;

instead of your

return Boolean(str === palindromic);

should produce the same result. But I’m curious to see if more experienced coders offer insights on benefits of using the Boolean constructor.

1 Like

Hi frtb0x!

I think the shorter one is better then the longer. Less variable, quick code, same result.
You can make it in one single line, if you miss out the symbol and the palindromic var.

Good way. Keep on going.

1 Like