user379888
user379888

Reputation:

JavaScript - Find if string is a palindrome - Check for punctuation

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

Upvotes: 0

Views: 4739

Answers (4)

P.Dederer
P.Dederer

Reputation: 62

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

Upvotes: 2

Cerbrus
Cerbrus

Reputation: 72947

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('');
}

Upvotes: 6

Pirate X
Pirate X

Reputation: 3093

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

Upvotes: -4

Muhammad Arslan Sajid
Muhammad Arslan Sajid

Reputation: 16

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

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

Upvotes: -3

Related Questions