Tell us what’s happening:
After building my code for the Palindrome challenge, I was grateful to have finished it but frustrated that I was quite different than the basic/ intermediate solutions offered in the help section - and way off from the advanced solution. I’ve added the advanced code below my solution.
My question is how do I approach solving problems in a way that helps me to learn best practices and avoid creating bad habits (or bad code) early on?
Your code so far
function palindrome(str) {
var string = str;
string = string.toLowerCase().replace(/\W+/g,"").replace(/\s+/g,"").replace("_","");
var newString = string.split("");
if (newString.join() === newString.reverse().join()) {
return true;
}
return false;
}
palindrome("1 eye for of 1 eye");
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/check-for-palindromes
//advanced example
function palindrome(str) {
// make all letters lowercase and remove non-alphanumeric characters
str = str.toLowerCase().replace(/[^a-z|1-9]/g, “”);
// if the length of the string is 0 then it is a palindrome
if (str.length === 0){
return true;
}
// if the first letter and the last letter of the string
// do not equal each other, then it is not a palindrome
if (str[0] !== str[str.length-1]){
return false;
}
//Else, run the function without the first and last characters.
else{
return palindrome(str.slice(1,str.length - 1));
}
}
palindrome(“mooo^&^%$m”);