rijo asked this 2 years ago

Javascript check if a string is palindrome

What is the most efficient way to check if a string is a palindrome?


Best Answer by ben100
2 likes

It would also be bettter to cache array.length so it does not have to be computed again and again:

function checkPal(str){
     temp = str.replace(/[^0-9a-z]/gi,'').toLowerCase().split('');
     var n = temp.length;
     for(var i=0;i<n/2;i++){
         if (temp[i] != temp[n-1-i])
         return false;
     }
     return true;
}

 

ben100 2 years ago
1 like

In a for loop:

function checkPal(str){
     temp = str.replace(/[^0-9a-z]/gi,'').toLowerCase().split('');
     for(var i=0;i<temp.length/2;i++){
         if (temp[i] != temp[temp.length-1-i])
         return false;
     }
     return true;
}
jsRant 2 years ago
1 like
return str == str.split('').reverse().join('');

Maybe a for loop is more efficient.