Palindrome("almostomla") should return false


Most of my code works, but I keep getting true for “almostomla”.
I have two var strings, with one being in reverse. I created for loops to compare the character for both strings. Not sure where the error lies.

function palindrome(str) {

  var outString = str.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'').toUpperCase();

  var newStr = outString.split().reverse().join().toUpperCase();

  for (var i = 0; i < outString.length; i++){

    for (var j = newStr.length -1; j > 0; j--)

      if (outString[i] === newStr[j]){

        return true;

      }else {

        return false;




  1. split takes an argument (what you want to split on). If you don’t provide one, then it will just give you the whole string back as an array: "ALMOSTOMLA".split() is ["ALMOSTOMLA"], ["ALMOSTOMLA"].reverse() is ["ALMOSTOMLA"], ["ALMOSTOMLA"].join() is "ALMOSTOMLA".
  2. join takes an argument (what the character is you are joining with). If you don’t provide one, it’s going to be , (comma). So if you fix 1, then you’ll end up with "A,L,M,O,T,S,O,M,L,A".
  3. You are returning in the loop if you get a match. This means loop exits the function ends if that is the case (the first letter of “ALMOSTOMLA” is “A”, so “A” === “A”, return true for function). You only need to return in the loop if the letters don’t match. Otherwise, if the loop finishes, then you can return true, as the word is the same backwards as forwards.
  4. You have nested loops, so the inner loop runs in full every time the first loop iterates. So if you fix 1 and 2 and 3, then what happens is: index 0 for outString is "A". index 9 for newStr is "A". index 8 for newStr is "L", exit now as "A" does not equal "L".

You have gone to the trouble of cleaning the string and producing a reversed version of it. Is there a way of comparing two string to see if they are the same? One that doesn’t involve loops?

Thank you for the detailed explanation. Almost forgot about the missing arguments.
var newStr = outString.split(’’).reverse().join(’’);
I really overthink what was being asked. Instead of nested for loops, I could simply use an equality operator and make a direct comparison since it was already reversed. Finally got it to work!

Thanks again for helping a novice coder.

1 Like