JavaScript Program To Check Whether a String is Palindrome or Not.
Problem: Write a function to check if a given string is a palindrome. A palindrome string is a sequence of characters that reads the same backward as forward. In other words, a string is a palindrome if reversing the string gives the same string.
Examples of Palindrome Strings.
- “radar”
- “level”
- “madam”
- “racecar”
- “A man, a plan, a canal, Pan
Approach 1:
function isPalindrome(str){ return (str.toLowerCase().split('').reverse().join('') == str.toLowerCase()) ? 'Palindrome String':'Not a Palindrome String' ; } console.log(isPalindrome('racecar')); Output: Palindrome String console.log('JavaScript'); Output: Not a Palindrome String console.log(isPalindrome('racecar')); Ouput: Palindrome String
Approach 2:
function isPalindrome(str){ let revstring = ''; for(let i=str.length-1;i>=0;i--){ revstring+=str[i]; } return (revstring.toLowerCase() == str.toLowerCase()? 'Palindrome String':'Not a Palindrome String'); } console.log(isPalindrome('racecar')); Output: Palindrome String console.log(isPalindrome('JavaScript')); Output: Not a Palindrome String console.log(isPalindrome('racEcaR')); Palindrome String