Post your Palindrome solutions here!

Heya folks!

Congrats on solving the palindrome project!! :partying_face:

Feel free to drop your solutions here.

Here’s mine:

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

function stringLowerCased(str){
  return str.toLowerCase();
}

const stringReversed = (str) => {
  let result =""
  for (let i=str.length-1; i >= 0; i--) {
    result += str[i]
  }
  return result;
}

function palindrome(str) {
  // Remove non-alphanumeric characters
  const cleanedUpStr = stringWithOnlyAlphaNumeric(str);

  // Make strings lowercase
  const lowercaseStr = stringLowerCased(cleanedUpStr);

  // Reverse the sting
  const reversedStr = stringReversed(lowercaseStr);

  // return the comparasion of:
  // Reversed stirng equals to? Lowercase cleanned up string
  return lowercaseStr== reversedStr;
}

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

Hey guys! This is my solution for the palindrome proyect. :smile:

function palindrome(str) {

  // REMOVE NON-ALPHANUMERIC AND UPPERCASE
    const cleanStr = str.replace(/[\W_]/gi, "").toLowerCase();

  // REVERSE
    const reverseStr = cleanStr.split("").reverse().join("");

  // COMPARE
    console.log(Is "${cleanStr}" equal to "${reverseStr}"?)
    return cleanStr == reverseStr;
}

console.log(palindrome("PAT-PAT"));
5 Likes

Not as readable as Ramón’s xD But still fun! :smiley:

function palindrome(str) {
  const checkStr = str.toUpperCase().match(/[a-z0-9]/ig)

  for (let i = 0; i<Math.floor(checkStr.length/2); i++){
    if (checkStr[i] != checkStr[checkStr.length-1-i]){return false}
  }
  return true;
}
4 Likes

I used Regex and a recursive function because I did not want to repeat the clean-up code for each recursion. I only did it this way simply for the challenge. It is not the simplest way.

function palindrome(str) {
  let lowStr = str.toLowerCase();
  let symRegExp = /[^a-z0-9]/g; // not alphanumeric characters
  let testStr = lowStr.replace(symRegExp, ""); // replace with ""
  console.log("Mod Str: ", testStr);
  let result = checker(testStr);
  return result
}

function checker(str) {
  if (str.length < 2){
    return "";
  }
  else {
    let test = false;
    let head = str.match(/^[a-z0-9]/);
    console.log(head[0]);
    let tail = str.match(/[a-z0-9]$/);
    console.log(tail[0]);
    if (head[0] === tail[0]) {
      test = true;
    }
    else {
      test = false;
    }
    console.log(test);
    if (str.length <= 2 || test === false) {
      console.log("Return: ", test);
      return test;
    }
    else {
      let bodyRegex = /(^[a-z0-9])(\w+)([a-z0-9]$)/;
      let body = str.replace(bodyRegex, '$2' );
      let pal = checker(body);
      return (pal === "") ? test : pal;
    }
  }
}

let resp = palindrome("_A man, a plan, a canal. Panama");
console.log("Result: ", resp);
4 Likes

Hey, maybe it’d be better to use ``` at the beginning and at the end of your code. So it’s correctly formatted :smiley:

1 Like

I wasn’t a fan of regex, but now I’m happy to use it and glad it worked!

function palindrome(str) {
  // Remove non-alphanumeric characters by replacing them with an empty string
  str = str.toLowerCase().replace(/[^a-z\d]/gi,"");
  // Reverse the string
  let reversedStr = str.split('').reverse().join('');
  return str === reversedStr;
}
2 Likes

I love this. This would be a utility function and its name tell you what it does. The only problem it also returns true for a single character.

1 Like

Thank you for your answer! :slight_smile:
I believe it could be more readable, but once you got what’s going on, it’s easy to get it.

And yeah, you’re right. Isn’t it supposed to be like that? I mean, if I read “m”, it’s the same both forward and backward.
But if you don’t want that to happen, it’s easy to add a if (checkStr.length == 1){return false}, or something similar :stuck_out_tongue:

Also, I just noticed that it’ll break if the match function on checkStr doesn’t match anything. Because checkStr would be Null, and we can’t .length a null variable.
So, two cases to treat at the beginning of the function :x

1 Like

I used the spread operator (I think! :wink: ) to convert the string to an array, so I could then use .reverse() But I had problems, where I couldn’t refer back to the original, but declared ORIGINAL to keep the pure text. Might be a ‘hacky’ solution, but I got it to work anyway.


  // remove all non-alphanumerics & make lowercase
  const originalStr = str.replace(/[\W_]/gi, "").toLowerCase();
  // KEEP ORIGINAL FOR LATER COMPARISON
  const ORIGINAL = originalStr;

  // convert originalStr to get reversed version, using spread operator
  const originalArray = [...originalStr];
  // reverse array in NEW variable to compare
  const reverseArray = originalArray.reverse();
  
  // convert back to string
  const textToCompare = reverseArray.join("");

  // compare
  return ORIGINAL == textToCompare;
}
2 Likes

So I had regular expressions stuck in my head and was initially trying to solve the whole thing with just those :sweat_smile:, but then I watched the video and as soon as Ramón said “loop” I knew what I could do!

function palindrome(str) {
//convert to lowercase, then use regex to replace any non-alpha-numeric characters in that string:
  let string = str.toLowerCase();
  let justString = string.replace(/[\W_]/gi, "");

//Create new string that reverses the modified string above, using a loop character by character:
  let reverseString = "";
  for (let i=justString.length-1; i >= 0; i--) {
    reverseString += justString[i];
  }
// Confirm the reversed string matches the original (returns true or false):
  return justString == reverseString;
}

:tada:

1 Like

I used recursion :sweat_smile:

const cleanUpStr = str => str.replace(/[\W_]/g, "").toLowerCase();

const stringReverse = (str, n) => {
  let reversedStr = "";
  if(n < 1) {
    return "";
  }
  reversedStr = str[n - 1] + stringReverse(str, n-1);
  return reversedStr;
}

function palindrome(str) {
  // Remove all non-alphamumeric characters and convert it to lowercase;
  const originalStr = cleanUpStr(str);
  
  // Reverse string
  const reversedStr = stringReverse(originalStr, originalStr.length);
  return reversedStr == originalStr;
}

console.log(palindrome("eye"));
console.log(palindrome("RaceCar"));
console.log(palindrome("not a palindrome"));
console.log(palindrome("_eye"));
console.log(palindrome("A man, a plan, a canal. Panama"));
2 Likes

Here’s mine. Phew!

//function to clean string: remove non-alphanumeric characters and make lower case
function cleanAlphaLowercase(str)
{
  //convert str to only alphanumeric characters, incl remove spaces & symbols
  const regEx = /[\W_]/g;
  const alphaStr = str.replace(regEx,'')
  //convert str to only lower case characters
  const alphaLowerStr = alphaStr.toLowerCase();
  return alphaLowerStr;
}

//function to reverse string: using built-in function method, string split, then reverse split
function reverseString(str)
{
  const cleanStr = cleanAlphaLowercase(str);
  const splitStr = cleanStr.split("");
  const reverseArr = splitStr.reverse();
  const reversedStr = reverseArr.join("");
  return reversedStr;
}

//function that compares clean and reversed strings to check if they're the same. if they are, the string is a palindrome and returns such a message.
function palindrome(str) 
{
  const forwardStr = cleanAlphaLowercase(str);
  const backwardStr = reverseString(str);
  console.log('forward: '+forwardStr);
  console.log('backward: '+backwardStr);
  console.log(`Is '${forwardStr}' equal to '${backwardStr}'?`);
  return forwardStr == backwardStr;
}

palindrome(" not a #paLinDRome_");
1 Like

Hi, here’s mine.
I made it as simple as I could.

function palindrome(str) {
    let palindromeRegex = /[a-z0-9]/ig; //This regex match only characters and digits
    let result = str.match(palindromeRegex); //An array only with characters and digits
    let strPal1 = result.join('').toLowerCase();//This concatenates the elements in the array, then converts the string to lowercase
    let strPal2 = result.reverse().join('').toLowerCase();//This reverses the elements in the array, concatenates them, and converts them to lowercase.
    if (strPal1 == strPal2) {
        // if true then it is a palindrome.
        return true; 
        
    } else {
        // if false it is not a palindrome.
        return false; 
    }

    
};

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

:grinning:

This is what I ended up with!

function palindrome(str) {
  let strnew = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
  return (strnew.split("").reverse().join("") == strnew)
}
1 Like

I first created a solution with split and join methods, but here’s a simple one just iterating the array back and for

function palindrome(str) {
  //first clean other chars from string
  let _cleanStr = str.replace(/[\W_]/ig, "").toLowerCase();
  //define matching true unless false
  let match = true;
  for (let i=0; i < _cleanStr.length; i++){
    //iterate _ckeanStr and compare to oposite position of the same string
   // this could be simplified to just iterate half of the string
    if (_cleanStr[i] !== _cleanStr[_cleanStr.length-1-i]){
      match = false
    }
  }
  //return result
  return match;
}
palindrome("eye");
1 Like

great!, this Math.floor(.length/2) is the part that my solution has to improve.

Hi, coders, this is my solution for the palindrome project, it’s works but any feedback is welcome, best regards and keep on coding! :smile:

function palindrome(str) {
const newString = str.replace(/[\W_]/gi, "").toLowerCase();
  
  let result = "";
  for(let i = newString.length -1; i >= 0; i--){
    result += newString[i];
  }
  if(result == newString){
    return true;
  } else{
    return false;
  }
}

palindrome("eye");

give me your thoughts :slightly_smiling_face:

function palindrome(str) {

let a = str.replace(/[^a-zA-Z0-9]/gi,"").toLowerCase();

return a==a.split("").reverse().join("");

}

palindrome(“eye”);

I tried it without creating a reversed string

function palindrome(str) {
 str=str.toLowerCase().match(/[a-z0-9]/g)
//convert the string to lowercase and remove unwanted characters
  for(var i=str.length-1; i>=0; i--) 
    //loop through the string

  { if(str[i]!==str[str.length-1-i])return false}
    //if first letter doesn't match the last break out of the loop
    //if they match move to the second and second last letter(repeat) 

return true}
  // if the loop finish return true

Hi guys,

Just sharing my solution to palindrome without using regex:

function palindrome(str) {

   let newStr = "";

  for(let i = 0; i < str.length; i++) {
    if (str[i] >= "A" && str[i] <= "Z") {
        newStr += str[i].toLowerCase();
     }
     else if (str[i] >= "a" && str[i] <= "z") {
        newStr += str[i];
     }
     else if (str[i] >= "0" && str[i] <= "9") {
        newStr += str[i];
     }
  }

  let reverseStr = "";

  for(let i = newStr.length - 1; i >= 0; i--) {
      reverseStr += newStr[i];
  }

  if (newStr === reverseStr) {
      return true;
  }
  else {
      return false;
  }

}