Check for Palindromes JavaScript help

I was trying to do this exercise using a for/while loop but couldn’t get the code to work so I solved it by comparing the reverse string and normal string. This is the code that I had whenI was using a while loop, why doesn’t this work?
In the while loop, I add in an if statement comparing each element in the str array and reverse str array and return false if they are not equal. Thank you for reading. Also apologies, I am unsure how to properly indent on the forum.

Hey. These are what I found:

  1. The while loop never increments i! Infinite loops are bad, but in this case, you never had any infinite loop becase…
  2. Your loop returns early. You should move return true; after the while loop, remove the else block, and add i++; before the loop’s ending }.
  3. This is interesting. .reverse() seems to reverse the array in-place. At this line var strReverse = strArray.reverse();, the original strArray itself is reversed (plus it creates a new reference to this reversed array called strReverse).
    So in this line if (strArray[i] !== strReverse[i]){, you’re actually comparing the array with itself. I fixed it by replacing strArray with strArrayDup (that’s probably your intention but you forgot; strArrayDup was never used in that code).

In the end this is what it looks like:

function palindrome(str) {
  // gets rid of blankspace and convert to lower case
  var newStr = str.replace(/[^0-9a-z]/gi, '').toLowerCase();
  // compare each element of array and reversed array
  var strArray = newStr.split('');
  var strArrayDup = strArray.slice();
  var strReverse = strArray.reverse();
  var i = 0;
  
  while (i < strArray.length) { // a for-loop would be better
    if (strArrayDup[i] !== strReverse[i]) {
      return false;
    }
    i++;
  }
  return true;
}
1 Like

type 3 backticks, press ENTER twice, type 3 backticks, paste code in between.

Whoops, I originally had i++ in there somewhere, I just typed this one up after completing it. Thanks for that.

Edit: Yep, I was supposed to use strArrayDup, I was staring at the code for too long wondering why hah!

Thanks for the super fast response kev by the way! Appreciate it, really nice to have someone looking over my code :smiley:

Nah, your post just happened to be on top of the forum when I visited :slight_smile:

You might do it easier.
After you’ve got the newStr you should create a reverseStr (smth. like newStr.split("").reverse().join("")) and then compare strings.

I straggled at this challenge because i couldn’t find out how to get rid of non-alphanumeric characters and this post helped me :slight_smile:

Well my code look like this now

` function palindrome(str) {
// Good luck!
var newStr = str.replace(/[^0-9a-z]/gi,"").toLowerCase();
var strReverse = newStr.split(’’).reverse().join(’’);

return newStr === strReverse;
}

palindrome("_eye");`

3 Likes

Here is what I used /// took me a few minutes but now makes sense:

function palindrome(str) {

// gets rid of blankspace and convert to lower case
var newStr = str.replace(/[^0-9a-z]/gi, ‘’).toLowerCase();
var results = “”;

for (i = newStr.length - 1; i >= 0; i–) {
results += newStr.charAt(i);
}
if (results === newStr) {
return true;
}
else {
return false;
}

}

palindrome(“eye”);

This was my solution,
Same as previous challenge, split reverse and join the string to set a reversed string as well as stripping out whitespace and punctuation.
At first i didn’t read the requirement to strip out punctuation so it might look messy,
Feedback welcome,

function palindrome(str) {
// Good luck!
var backwards =str.toLowerCase().replace(/ /g, ‘’).replace(/[.,/#!$%^&*;:{}=-_~()]/g,"").split('').reverse().join(''); var forwards =str.toLowerCase().replace(/ /g, '').replace(/[.,\/#!$%\^&\*;:{}=\-_~()]/g,“”);
console.log(forwards+" / "+backwards);

if (backwards === forwards){
return true;
}
return false;
}
palindrome(“eye”);

cade you please tell me what is wrong with my code?

function palindrome(str) {
var newStr = str.replace(/[^0-9a-z]/gi, ’ ').toLowerCase();
var newArray = newStr.split("");
var newReverse = newArray.reverse("");
var newJoin = newReverse.join("");
if (str == newJoin ){
return true;
}
else {
return false;
}
}

palindrome(“race car”);

function palindrome(str) {

var newStr = str.replace(/[^0-9a-z]/gi, ‘’).toLowerCase();
var newNewStr = newStr.split(’’).reverse();
var compareString = newNewStr.join(’’);

if (compareString == newStr)
{ return true;}

else {
return false;
}
}

Hi this is my working code;

function palindrome(str) {
  var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
  var checkPalindrome = removeChar.split('').reverse().join('');
  if(removeChar === checkPalindrome) {

  return true;
}  
  return false;
}

palindrome("eye");

If your condition (removeChar === checkPalindrome) equals true you return true else you return false. So it can be simplified as
return (removeChar === checkPalindrome);

1 Like

Of course. :slight_smile:

can somebody explain to me how the regular expression str.replace(/[^A-Z0-9]/gi, “”)

works?

thanks a bunch!

To explain further, the ^ means not only when it’s the first character inside brackets (like in the example). Outside, the ^ means the start of a line (so /^cat/ will match the 'cat' in 'caterpillar' but not the 'cat' in 'housecat').

2 Likes

So, here is my code. I think the reason my code is not working is because it is not eliminating the spaces. If anyone can tell me what is wrong it would be appreciated!

function palindrome(str) {
var passStrings = str.replace(/[^A-Z0-9]/gi,’’).toLowerCase();
var output = passStrings.split("").reverse().join("");//[“e”, “y”, “e”]

if (output === str) {
return true;
}
else{
return false;
}

// Good luck!

}
palindrome(“eye”);

ahhh, awesome man, thanks!

Here, I found the solution for your problem. Firstly, despite of using the reversed version of your array. You just have to go from the beginning of array to the middle element in your array. There, you will check by FIRST and LAST. So, here is my code:

function palindrome(str) {
    var len = str.length;
    for ( var i = 0; i < Math.floor(len/2); i++ ) {
        if (str[i] !== str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}