bikedres bikedres - 1 month ago 10
Javascript Question

Trying to create a palindrome function that accounts for spaces

Okay so palindrome is a word that is the same spelled backwards. What if we want to take a phrase that is also the same backwards? So

kook
is one.
race car
is another one.

So I made one that doesn't account for spaces.

function isPal(string){
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}


This one works fine for words.

Now I'm thinking, push the string into an array, and split up each character into it's own string, then remove any spaces, and then run
if (string.charAt(i) != string.charAt(string.length - i - 1))
. So here's what I wrote but failed at..

function isPalindrome(string){
var arr = [];
arr.push(string.split(''));
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);


if I return
arr
, it still gives me the string with the space in it. How do I accomplish this? Thanks!

EDIT: Used the solution but still getting false on 'race car'
Here's what I got:

function isPalindrome(string){
var arr = string.split('');
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
} else if (arr[i] != arr[arr.length - i - 1]){
return false;
}
}
return true;
}


where's my error?

Answer

Your problem is in the following line:

arr.push(string.split(''));

string.split('') returns an array. So, arr is actually an array with one entry it in (another array that contains your characters). Replace:

var arr = [];
arr.push(string.split(''));

with

var arr = string.split('');

and it should work as expected