Not sure what i did wrong. I'm trying to compare 2 strings to see if they are Palindromes
function palindrome(str) {
var rem = str.replace(/\s/g, "");
var a = rem.split("");
var b = a.reverse();
for(var i = 0; i < rem.length; i++){
if (b[i] == a[i]){
return true;
}
return false;
}
}
palindrome("not a doctor"); //this should show false, but it's showing true
There are a few problems with your code.
Problem 1: You are using reverse
method which mutate the original array (See the docs on reverse). So variables a and b would have the same value, that is the reversed string of the original array. What you can do instead is create a fresh new array and assign it to the variable b
like so:
var b = [].concat(a).reverse();
Problem 2: You forgot to check ALL of the letters in the string. You are returning your function way too early. For example, for the input string 'aada', which is not a palindrome it will return true. This is because, your function exits as soon as evaluates the similarity of the first string of both arrays. To fix this you could do something like this:
function palindrome(str) {
var rem = str.replace(/\s/g, "");
var a = rem.split("");
var b = [].concat(a).reverse();
for(var i = 0; i < rem.length; i++){
if (b[i] !== a[i]){
return false;
}
}
return true
}
You can even further optimise your function like this:
function palindrome(str) {
const len = str.length;
const halfLen = len/2;
for (let i = 0; i < halfLen; i++) {
if (str[i] !== str[len - 1 - i]) return false;
}
return true;
}
Palindrome strings read the same backwards and forwards, So you can make a comparison of the first and the last, second to second last etc until you reach the middle character.
Hope this helps.