Skip to content

Instantly share code, notes, and snippets.

@deepakkj
Last active August 29, 2017 17:30
Show Gist options
  • Save deepakkj/e7b049413831339a103fc1a3ec1a3102 to your computer and use it in GitHub Desktop.
Save deepakkj/e7b049413831339a103fc1a3ec1a3102 to your computer and use it in GitHub Desktop.
Check if a string is a palindrome or not? - Efficient Method
//using normal reversing techinque
function palindrome1(str){
//removing space and non-alphanumeric characters;
str = str.toLowerCase().replace(/[^0-9|a-z]/g,'');
//reversing the string
var str2 = str.toLowerCase().replace(/[^0-9|a-z]/g,'').split('').reverse().join('');
//checking if both are equal
if(str === str2)
return true;
else
return false;
}
console.log(palindrome1("e ye"));
//using half then number of characters for comparison
function palindrome2(str){
//removing space, non-alphanumeric characters
str = str.toLowerCase().replace(/[^0-9|a-z]/g,'');
//
for(var i=0; i<str.length/2; i++){
if(str[i] !== str[str.length - i -1]){
return false;
}
}
return true;
}
console.log(palindrome2("e ye"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment