A string is palindrome if we read it from end to the beginning and it is the same as begin to end. The logic to detect wheter a word is palindrome or not in programming is very simple, you need to remove the special characters from the string and reverse the result. If the strings are equal (the filtered and the reversed filtered string) then the string is palindrome, pretty easy right? In this article, we'll show you how to follow the mentioned logic with a JavaScript function easily.
Verifying with a basic function
Following the mentioned logic, we'll simply create a variable that will contain the stringthat we need. As first, we convert all the characters of the string to its lowercase version, then we remove special characters and finally compare the strings, if they're equal, the function will return a boolean that confirms it:
/**
* A function that verifies wether the given string is Palindrome or not.
*
* @returns {Boolean}
*/
function isPalindrome(str){
var normalized = str.toLowerCase().match(/[a-z]/gi).reverse();
return normalized.join('') === normalized.reverse().join('');
}
So, you can cast the isPalindrome
method providing a string as first argument and this will return a boolean that notices wether it's or not:
if(isPalindrome("Go dog.")){
console.log("Is Palindrome");
}else{
console.log("It's not Palindrome");
}
Verifying with a prototype function
If you are willing to test if a string is palindrome without providing it as first argument of any function, as long as the variable is a string, you can create a shortcut so to speak by extending the String prototype and creating your own function for it. In this way you can call the isPalindrome
method as if it were a property of the string e.g:
/**
* An extension function for strings that allows you to verify
* wether the string is Palindrome or not.
*
* @returns {Boolean}
*/
String.prototype.isPalindrome = function () {
var normalized = this.toLowerCase().match(/[a-z]/gi).reverse();
return normalized.join('') === normalized.reverse().join('');
}
So, you can cast the isPalindrome
method for a string and this will return a boolean that notices wether it's or not:
if("Go dog.".isPalindrome()){
console.log("Is Palindrome");
}else{
console.log("It's not Palindrome");
}
Further examples:
// True
"A Toyota! Race fast, safe car! A Toyota!".isPalindrome()
// True
"A car, a man, a maraca.".isPalindrome()
// True
"Eye".isPalindrome()
// False
"Never even or odd".isPalindrome()
Happy coding !