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!