Check for Palindromes JavaScript help

Check for Palindromes JavaScript help
0

#1

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.


#2

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;
}

#3

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


#4

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!


#5

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


#6

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


#7

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.


#8

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");`


#9

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”);


#10

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”);


#11

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”);


#12

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;
}
}


#13

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");

#14

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


#15

@dvainf You can also ditch the ( )


#16

Of course. :slight_smile:


#17

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

works?

thanks a bunch!


#18

Sure.
str.replace(/[^A-Z0-9]/gi, “”) will return a new string by replacing all the characters in str which are NOT a letter or number (case insensitive) with a blank ("").
The g means all instances
The i means case insensitive
The ^ means Not

Hope that helps.


#19

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').


#20

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”);