Post your Palindrome Checker solutions here!

Heya folks!

Congrats on solving the palindrome checker project!! :tada:

Feel free to drop your solutions here.

Here’s mine:

function cleanUpNonAlpha(str) {
  return str.replace(/[\W_]/g, "");
}

function makeUppercase(str) {
  return str.toUpperCase();
}

function flipStr(str) {
  // Take an empty string
  let result = "";

  // Start a loop at the end of the input string
  //    Put the letter at the current stage at the end of the result string
  for(let i=str.length-1; i>=0; i--) {
    result += str[i];
  }
  
  // return result string
  return result;
}

function palindrome(str) {
  // Clean up string by removing non-alphanumeric characters
  const cleanedUpStr = cleanUpNonAlpha(str);

  // Make cleaned up string uppercase
  const uppercaseStr = makeUppercase(cleanedUpStr);

  // Reverse uppercase cleaned up string
  const reversedStr = flipStr(uppercaseStr);

  // Compare reversed and uppercase string
  // If they're the same, it's a palindrome (return true)
  console.log(`Is ${uppercaseStr} the same as ${reversedStr}?`)
  return reversedStr === uppercaseStr;
}

console.log(palindrome("Tacocat!"));
2 Likes

Here’s mine:

function palindrome(str) {
//remove alpha numeric characters
const cleanStr = str.replace(/[\W_]/g , “”);
console.log(cleanStr);
//make the string uppercase
const newStr = cleanStr.toUpperCase();
// check
for(let i = 0; i < newStr.length;i++ ){
if (newStr[i] === newStr[(newStr.length - 1)-i]){
continue;
} else {
return false;
};
}
** return true**;
}
console.log(palindrome(“_eye”));

6 Likes

Hi guys and gals!!

This is my solution. I have commented out trying to explain it. I hope my english didn’t get too tricky. :crazy_face:

Even though my solution seems more fancy, for this challenge an old fashion loop is probably a better aproach. The code is longer but more readeable, readability is really important.

Here it goes:

function palindrome(str) {

  // Clean up the string: 
  // 1 | replace all non alphanumerics characters and underscores from the string using regex (/[\W_]/g)
  //     and replace method, wich sustitutes all with an empty string
  //     -->  fivefour is the result
  // 2 | convert all characthers to lower case  
  const cleanedUpStr = str.replace(/[\W_]/g, "").toLowerCase();

  // Reverse the order of the string letters
  // 1 | Convert the cleaned string into an array using the spread operator ([...string])
  //     --> [ 'f', 'i', 'v', 'e', 'f', 'o', 'u', 'r' ] is the result
  // 2 | Reverse the resulting array items using Array.prototype.reverse() method
  //     --> [ 'r', 'u', 'o', 'f', 'e', 'v', 'i', 'f' ] is the reversed array
  // 3 | Join all the items in a single string using Array.prototype.join("") method, no spaces ("", empty string is used)
  //     --> ruofevif is the resulting reversedStr variable
  const reversedStr = [...cleanedUpStr].reverse().join("");

  // Console log the obtained variables and too actually see it
  console.log({cleanedUpStr}, {reversedStr});

  // Return a boolean comparing both variables
  return cleanedUpStr === reversedStr;
}

palindrome("five|\_/|four");

You can use this tool JavaScript coding tutor - Learn JavaScript by visualizing code execution to visualize the result of any code step by step. It is a brilliant recomendation from @syllie; read her posts, they are really well documented and well explained ones.

Keep calm, keep going and dont give up. You ALL can do it!!! :fist:
Happy coding!

4 Likes

That’s my solution - maybe a bit complicated as I haven’t done yesterday’s homework before writing it. I had a bit of a hard time figuring out how to test the arrays for equality (the toString() method), as I forgot that we cannot check the arrays directly for equality.

function palindrome(str) {
  //regex to get rid of symbols and make everything uppercase:
  let myRegex = /[a-z0-9]/gi;
  let strUpper = str.toUpperCase();
  strUpper = strUpper.match(myRegex);

  //find length of the clean string:
  let laenge = strUpper.length;

  //reverse the string
  let strBackwards = [];

  for (let i = 0; i < laenge; i++) {
    strBackwards.unshift(strUpper[i]);
  }

  
  //as arrays cannot be directly tested for equality, I changed them to strings
  if (strUpper.toString() == strBackwards.toString()) {
    return true;
  } else {
    return false;
  }
}

console.log(palindrome("1 eye for of 1 eye."))

8 Likes

Hi @sandrahirsch2923199

I would recommend you use always the strict equality === operator to avoid issues and keep your variables under your control not under JavaScript.

Your solution looks great!
The code is clean and It is also easier to read and understand than mine, so be proud!!

Happy coding! You are doing great!

3 Likes

thanks for the feedback - much appreciated :smiling_face:

3 Likes

I really like your approach for the loop - that was what I was looking for, but my brain didn’t figure it out :wink:

3 Likes

I did three solutions, but here is the shortest one:

4 Likes

I did three solutions and this is the shortest one:

function palindrome(str) {
  let newStr = str.toLowerCase().replace(/[^a-z\d]/g, "");
   return newStr.split("").reverse().join("") === newStr;
 }
console.log(palindrome("A man, a plan, a canal. Panama"));
5 Likes

You still got too much lines, fixed that for you, no need to thank me :rofl:

const palindrome = str => str.toLowerCase().replace(/[^a-z\d]/g, '') === str.toLowerCase().replace(/[^a-z\d]/g, '').split('').reverse().join("");

I tend to not introduce new variables when I can reuse them…have to be careful with arrays :sweat_smile:
My solution:

function palindrome(str) {
  str = str.replace(/\W|_/g, ""); //remove non-alphanumeric characters
  str = str.toUpperCase(); // all characters to uppercase
  for (let i = 0; i <= str.length / 2; i++) {
   //compare first letter to last letter etc
   if (str[i] !== str[str.length - 1 - i]) {  
     return false;
   }
  }
  return true;
}
6 Likes

Mine was like yours except for using the spread operator, I went for the more traditional const reversed = result.split('').reverse().join(''); :slight_smile:

4 Likes

lmao :rofl: love how you fixed @Timiphil 's code so it becomes a one liner. I pity the developer that someday has to fill your shoes. love your humour!

3 Likes

Damn! How did you do that? That’s cool. I want to learn that.

I wanted to do my solution before watching the video so I guess this is not quite as elegant as it could be. I am sure I don’t need \s+ in my variable nospace and I am fairly sure I don’t need to bring the const newPhrase in at all!!

But, what the heck, it works and I think that is what counts - love some of the shortcuts some of you folk have used and I hope we get to learn them soon. But compared to my (also working) solution for Roman Numerals, this is positively glowing with elegance!!!

Cheers folks

Bill

function palindrome(str) {
 let nospace = /\s+|\W+|_/gi; 
 let replace = (str.replace(nospace,"")); 
 const newPhrase = replace.toLowerCase();
  for(let i = 0; i < newPhrase.length; i++){  
    if(newPhrase[i] === newPhrase.charAt(newPhrase.length-i-1)){     
    }else{
     return false;
    }
  }
  return true;
}
palindrome("almostomla")
4 Likes

Here’s my solution below.

Thanks,
Michael

// removes all non-alphanumeric characters
function cleanUpNonAlpha(str) {
let fixRegex = /\W|_/g; // Change this line
let replaceText = ‘’; // Change this line
return str.replace(fixRegex, replaceText);
}

// reverses string
function reverse(str) {
let result = ‘’;
for (let i = str.length - 1; i >= 0; i–) {
result += str[i];
}
return result;
}

function palindrome(str) {
let strippedStr = cleanUpNonAlpha(str);

// make string lowercase
strippedStr = strippedStr.toLowerCase();

// return
const reversed = reverse(strippedStr);

return strippedStr === reversed;
// return reversed;
}

palindrome(‘eye’);

4 Likes

That’s an arrow function with parameters, it was introduced at the beginning von ES6, maybe you forgot it already, and then substituting newStr in the return statement with your definition of newStr. :innocent:
It’s kinda the same function but less readable.

When you wrote that was your shortest solution, my fingers just started itching to help you changing it into one line :rofl:

4 Likes

Here’s mine- I was following along with Ramón, so the start is the same, then I paused the lesson and broke away and finished the checker with help from MDN and previous lesson notes.

function cleanUpNonAlpha(str) {
return str.replace(/[\W_]/g, “”);
}

function makeUppercase(str) {
return str.toUpperCase();
}

function flipStr(str) {
return str.split(“”).reverse().join(“”);
}

function palindrome(str) {

const cleanedUpStr = cleanUpNonAlpha(str);

console.log(cleanedUpStr);

const uppercaseStr = makeUppercase(cleanedUpStr);

console.log(uppercaseStr)

const reversedStr = flipStr(uppercaseStr);

console.log(reversedStr);

return uppercaseStr === reversedStr?
true: false;

// If they are the same, it’s a palindrome (return true)

}
console.log(palindrome(“otto”));
palindrome(“Otto”);

4 Likes

So I did 2 versions. First up a recursive function just because I wanted to practice this.

/*
So, I wanted to have a play writing a recursive function to do this just for the practice.
Even though there is a much simpler way to do it (reversing the string and checking equality).
Recursion logic:
- start with full string e.g. tacocat
- compare first and last characters (= t and t)
- they are a match so a recursive call to same function with substring
  excluding these characters - so this case string will be acoca
- and so on until either first and last chars don't match - not palindrome or reach base case
- base case is length of zero or one characters - if this is reached, the string is a palindrome.
 */

function recursiveIsPalindrome(str) {
    // if the string has been reduced down to one or no chars, all previous pairs of
    // first and last chars match so the string is a palindrome
    if (str.length <= 1 ) {
        return true;
    }
    else if (str.charAt(0) === str.charAt(str.length - 1)) {
        // if first and last char in string are a match, recursive call of this function with a substring
        // excluding these characters.
        return recursiveIsPalindrome(str.substring(1, (str.length - 1)));
    }
    else {
        // if characters don't match, definitely not a palindrome, no further checking needed.
        return false;
    }
}

function palindrome(str) {
    // convert string to lower case and strip out all non alphanumeric chars
    let testString = str.toLowerCase().replace(/[^a-z0-9]/g, "");
    console.log(`Original string = ${str}, stripped string = ${testString}`);
    // check if converted string is a palindrome
    return recursiveIsPalindrome(testString);
}

console.log(palindrome("eye")); //should return true.
console.log(palindrome("_eye")); //should return true.
console.log(palindrome("race car")); //should return true.
console.log(palindrome("not a palindrome")); //should return false.
console.log(palindrome("A man, a plan, a canal. Panama")); //should return true.
console.log(palindrome("never odd or even")); //should return true.
console.log(palindrome("nope")); //should return false.
console.log(palindrome("almostomla")); //should return false.
console.log(palindrome("My age is 0, 0 si ega ym.")); //should return true.
console.log(palindrome("1 eye for of 1 eye.")); //hould return false.
console.log(palindrome("0_0 (: /-\ :) 0-0")); //should return true.
console.log(palindrome("five|\_/|four")); //should return false.

Second when I started watching the class video and realised just reversing the string was much simpler.

function palindrome(str) {

    console.log("Original string: " + str);
    // convert string to a single case (all lower)
    const lowerCaseStr = str.toLowerCase();

    // Clean up string by removing non-alphabetic characters
    const cleanedUpString = lowerCaseStr.replace(/[^a-z0-9]/g, "");
    console.log("Cleaned up string: " + cleanedUpString);

    // reverse string
    // Thank you https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/
    // then later "Lukas" during the Class Central video session
    // for this info on how to reverse a string.
    const reversedString = cleanedUpString.split("").reverse().join("");
    console.log("Reversed string: " + reversedString);

    // compare original cleaned up string and reversed string
    // if they match, string is a palindrome
    return cleanedUpString === reversedString;
}

console.log(palindrome("eye")); //should return true.
console.log(palindrome("_eye")); //should return true.
console.log(palindrome("race car")); //should return true.
console.log(palindrome("not a palindrome")); //should return false.
console.log(palindrome("A man, a plan, a canal. Panama")); //should return true.
console.log(palindrome("never odd or even")); //should return true.
console.log(palindrome("nope")); //should return false.
console.log(palindrome("almostomla")); //should return false.
console.log(palindrome("My age is 0, 0 si ega ym.")); //should return true.
console.log(palindrome("1 eye for of 1 eye.")); //hould return false.
console.log(palindrome("0_0 (: /-\ :) 0-0")); //should return true.
console.log(palindrome("five|\_/|four")); //should return false.

hope these help someone.

3 Likes

Here goes my solution, I had trouble with the regex expression as I was not familiar with the .replace() method

function palindrome(str) {
  const justAlpha = str.replace(/\W|_/g, "").toLowerCase()
  const reversedStr = justAlpha.split("").reverse().join("")
  return (justAlpha === reversedStr ? true : false);
}

5 Likes

Way to go Jane!

Only thing I want to point out is that your ternary operator in the return is a bit overboard. Remember that the conditon uppercaseStr === reversedStr already evaluates to either true or false, so no need to make it explicitly. You could do just

return uppercaseStr === reversedStr;

But you have this! Well done!

@damian2665429 - this one is for you too! :slight_smile: well done!

2 Likes