What is the most efficient way to check if a string is a palindrome?
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;
}
return str == str.split('').reverse().join('');
Maybe a for loop is more efficient.
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;
}