Check for Palindromes by using cycle

Check for Palindromes by using cycle
0

#1

Tell us what’s happening:
hello, guys! this code all doing well excluding non-palindrome word ‘almostomla’. Could you help me to understand what is wrong?

Your code so far

function palindrome(str) {
  str = str.toLowerCase();
  
  var letterFinder = /[\a-z\d]/gi;
  var onlyLetter =str.match(letterFinder);
  var onlyLetter2 = str.match(letterFinder);
  var reverserL = onlyLetter.reverse();
 
  var result; 
  var a;
  var b;
  
   for (var i = 0; i < onlyLetter.length; i++) {
      a = onlyLetter[i];
     for (var j = 0; j < onlyLetter2.length; j++) {
       b = onlyLetter2[j];       
       } result = a[i] === b[i];
        
     } result = a==b;
 
   return result;

}



palindrome("My age is 0, 0 si ega ym.");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:


#2

Since the input and the reversed input has the same length you only need one loop
try this

function palindrome(str) {
  var string = str.toLowerCase();
  var stringReversed = string.match(/[\a-z\d]/gi).reverse();
  var stringnorml = string.match(/[\a-z\d]/gi);
   for (var i = 0; i < stringnorml.length; i++) {
     if(stringnorml[i] != stringReversed[i])
       return false;
   }
   return true;
}

#3

Not sure if you realize this, but onlyLetter2 is an array of the the string letterFinder and onlyLetter is an array of letterFinder in reverse order.

The following line is what reverses onlyLetter.

var reverserL = onlyLetter.reverse();

In the last line before return result, you have:

result = a==b;

Your code is always going to return true if the first and last letter of the letterFinder string are the same and false if they are not.

Why? During the last iteration of the outer for loop, the value of a will be the last element in the onlyLetter array (1st letter in letterFinder because onlyLetter is in the reverse order of letterFinder). The inner for loop of your code is not really accomplishing anything, because the value of b of any given iteration of the outer loop will always be the last element of onlyLetter2 (which is the last letter in letterFinder).

The following results from your code:

palindrome("eye") // correctly returns true because first and last letters match
palindrome("ets") // correctly returns false because first and last letters do not match
palindrome("eyse") // incorrectly returns true because first and last letters match

#4

thank you very much, your help was very useful!!!


#5

thank you, Randell. You show me the problem.