Palindrome Solutions

I’ve been trying to write a palindrome function for the following algorithm challenge: https://www.freecodecamp.org/challenges/check-for-palindromes

Can anybody tell me why the code below isn’t returning any ‘false’ statements?
Thank you in advance.

function palindrome(str) {
strInLowerCase = str.toLowerCase();
readForward = strInLowerCase.replace(/[^a-z 0-9]+$/g);
readBackward = readForward.split().reverse().join("");
if (readBackward == readForward) {
return true;
}
return false;
}

palindrome(“not a palindrome”);

Stick the following right before the if statement and see why it is not returning false:

  console.log(readForward);
  console.log(readBackward)

Your split function is not correct.

Also, your regular expression has an error also. You do not specify what you want to replace with.

I’d like to replace only the alphanumeric characters in the original string with
.replace("", /[^a-z 0-9]+$/g). I’m not quite sure how to go about this.

RegEx is the key to eliminate the special characters. Did you validate your regular expression?

I passed the challenge with this function. There has to be a cleaner, simpler way to write it.

function palindrome(str) {
// turn letters into lowercase, replace letters
var strInLowerCase = str.toLowerCase();
var strPunctuationless = strInLowerCase.replace(/[.,/#!$%^&*;:{}=-_`~()]/g,"");
var strSpaceless = strPunctuationless.replace(/\s{1,}/g,"");
var readForward = strSpaceless;
var readBackward = readForward.split("").reverse().join("");
if (readBackward == readForward) {
return true;
}
return false;
}

palindrome(“not a palindrome”);

Below was my approach to clear the challenge

function palindrome(str) {
  var cleanString = str.replace(/[^A-Z0-9]/ig, "_").replace(/_/ig, "").toLowerCase();  
  return (cleanString == Array.from(cleanString).reverse().join(""));
}
1 Like

Does .replace(/[^A-Z0-9]/ig, “_”) not delete uppercase letters? How did you then change them to lowercase letters with .replace(/_/ig, “”).toLowerCase()?

.replace(/[^A-Z0-9]/ig, “_”) - Will replace all special characters except to “_”
.replace(/_/ig, “”).toLowerCase() - This 2 operations replace all _ to “” and convert all to lowercase.

I did not write a single expression to both at once. We can optimize the RegEx

@samee.ks

var cleanString = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();

Thanks !
That was so lame

I’m still confused. To me, .replace(/[^A-Z0-9]/ig, “_”) gives the command to replace /[^A-Z0-9]/ig with “_”, not to ignore “_”. .replace(/_/ig, “”) looks to be formatted the same as .replace(/[^A-Z0-9]/ig, “_”) yet gives a different command. What am I missing?

For Check for Palindromes, the advanced solution includes .match() methods to replace any non-alphanumeric characters. Why use .match() when it is supposed to return an array with the the corresponding string characters? Like most people, I had only thought of .replace().

match was not used to replace any non-alphanumeric characters. It was used to test if the current character (either str[front] or str[back]) was an alphanumeric character. If it was not, then the next character was examined via incrementing/decrementing front/back. The following could have been used instead of the match statements and worked exactly the same.

while ( str[front].match(/[\W_]/) ) {

could have been replaced with:

while ( /[\W_]/.test(str[front]) ) {

AND

while ( str[back].match(/[\W_]/) ) {

could have been replaced with:

while ( /[\W_]/.test(str[back]) ) {

Ahhh - I see! The entire function make more sense now. Thanks!

function palindrome(str) {
// Good luck!
var lStr = str.toLowerCase(str);
var char_array = lStr.match(/[a-z0-9]/g);
var start = 0;
var end = char_array.length - 1;
for (start; start <= end; start++) {
if (char_array[start] !== char_array[end]) {
console.log(char_array[start]);
console.log(char_array[end]);
return false;
} else {
–end;
}
}
return true;
}
palindrome(‘almostomla’);

Nice and easy :slight_smile:

function palindrome(str) {
// Good luck!
var remove = str.replace(/[^A-Z0-9]/ig, “”).toLowerCase();
var check = remove.split(’’).reverse().join(’’);

if (remove=== check){
return true;
} else return false;
}

palindrome(“eye”);`

Hi guys,

I’d like to share my solution here:

function palindrome(str) {
  str = str.toLowerCase().replace(/\W/g, '').replace('_','');
  var arr = str.split('');
  var firstArr = arr.slice(0,Math.floor(arr.length / 2));
  var secondArr = arr.slice(Math.ceil(arr.length / 2));
  return firstArr.join() == secondArr.reverse().join();
}

My approach takes longer I believe, but is a bit different:

function palindrome(str) {
  // split the input into an array
  var array = [];
  var string = str.toLowerCase();
  // filter array of white space and non alphanumeric values
  string = string.replace(/[^0-9a-z]/gi, '');
  array = string.split("");
  // Create first and last letter to compare
  var firstChar;
  var lastChar;
  var length = Math.floor((array.length)/2);
  // Compare using a for loop at lenght/2
  for(var i = 0; i < length; i++){
    firstChar = array.shift();
    lastChar = array.pop();
    
    if (firstChar !== lastChar){
      return false;
    }
  }
  // If statement, if a != b then false
  return true;
}

A post was split to a new topic: Why does my Palindrome solution pass all but one test?

Here’s my code. How can I make it better?

function palindrome(str) {
// Good luck!
var firstStr = str.toLowerCase();
var secStr = firstStr.replace(/\s/g, “”);
var thirdStr = secStr.replace(/[. ,:-_-/()]+/g, “”);
var arr = [];
arr= thirdStr.split(’’);

newArr = arr.reverse();

var joinArr = newArr.join(’’);

if(joinArr === thirdStr){
return true;
}
else{
return false;
}

}