Skip to content

Instantly share code, notes, and snippets.

@msaxena25
Last active January 3, 2019 13:03
Show Gist options
  • Save msaxena25/e80451a409c76183288362e0ee8a04fc to your computer and use it in GitHub Desktop.
Save msaxena25/e80451a409c76183288362e0ee8a04fc to your computer and use it in GitHub Desktop.
JavaScript Check Palindrome
function checkPalindrome(str) {
if(str) {
var pattern = /[^a-zA-z]+/g; // first remove spaces and special chars from given string
str = str.replace(pattern, '').toLowerCase();
var str1 = str.split('').reverse().join('');
console.log(str, str1); // for testing
if(str1 == str.toLowerCase()) {
return true;
}else {
return false;
}
}
}
Output >
checkPalindrone("diD") => true
// Second method without using any predefined method :
function checkPalin(str) {
var pattern = /[^a-zA-z]+/g;
var output = "";
var input = str.replace(pattern, '').toLowerCase();
for(var item of input) {
output = item + output;
}
if(input == output) {
return true;
}else {
return false;
}
}
Ouput >
checkPalin("Cigar? Toss it in a can. It is so tragic")
result is true
example : https://codepen.io/mfenton/pen/OjyGEN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment