Last active
January 3, 2019 13:03
-
-
Save msaxena25/e80451a409c76183288362e0ee8a04fc to your computer and use it in GitHub Desktop.
JavaScript Check Palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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