0

I am trying to solve an exercise but the code shows errors. Here are the conditions given for the exercise:

Return true if the given string is a palindrome. Otherwise, return false.

  1. You'll need to remove punctuation and turn everything lower case in order to check for palindromes.
  2. We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.

My attempt:

function palindrome(str) {
    str = str.toLowerCase();
    str = str.replace(",", "");
    str = str.replace(".", "");
    str = str.replace(":", "");
    str = str.replace(";", "");
    str = str.replace("-", "");
    str = str.replace(",", "");
    str = str.replace(" ", "");
    for (var i = 0; i <= (str.length / 2); i++) {
        if (str[i] != str.length - i) return false;
    }
    return true;
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

4 Answers4

6

You were quite close.
Replace:

if (str[i] != str.length-i)

With:

if (str[i] != str[str.length - (i + 1)])

The last character of the string is at str.length - (i + 1), and you forgot to get the actual character. Instead, you were comparing it with the index of that character.

Now, you could shorten the function a lot:

function checkPalindrome(str) {
    // remove punctuation, to lower case.
    str = str.replace(/[.,?:;\/() _-]/g, '').toLowerCase();
    // Compare the string with it's reversed version.
    return str == str.split('').reverse().join('');
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
2

My solution for the problem:

function palindrome(str) {
    return str.toLowerCase() == str.toLowerCase().split('').reverse().join('');
}

In terms of performance this solution is faster than using a for loop or regular expression

P.Dederer
  • 62
  • 3
-3

This is quite simple. just make and call below function:

var isPalindrome = function(str){ return str == str.split('').reverse().join(''); }

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

Optimized version

Source : See here

Community
  • 1
  • 1
Pirate X
  • 3,023
  • 5
  • 33
  • 60