This tutorial shows how to check whether a given string is palindrome or not using JavaScript. A string is said to be a palindrome if it is spelled the same from forward and backward. For example, “madam” is spelled the same from forward and backward. so, it is a palindrome. In JavaScript, we can use for loop or the built-in functions to check if a string is palindrome or not.
Example 1: Check Palindrome String Using for Loop
// program to check if the string is palindrome or not
function CheckPalindrome(str) {
// find the length of a string
const len = str.length;
// loop through half of the string
for (let i = 0; i < len / 2; i++) {
// check if first and last string are same
if (str[i] !== str[len - 1 - i]) {
return 'It is not a palindrome';
}
}
return 'It is a palindrome';
}
console.log(CheckPalindrome("madam"));
console.log(CheckPalindrome("fruit"));
Output
It is a palindrome
It is not a palindrome
Example 2: Check Palindrome String using built-in Functions
// program to check if the string is palindrome or not
function CheckPalindrome(str) {
// reverse the string
let reverseStr = str.split("").reverse().join("");
if(str === reverseStr) {
return 'It is a palindrome';
}
else {
return 'It is not a palindrome';
}
}
console.log(CheckPalindrome("madam"));
console.log(CheckPalindrome("fruit"));
Output
It is a palindrome
It is not a palindrome