JavaScript: Check a string for palindromes using recursion
JavaScript Function: Exercise-10 with Solution
Recursive Palindrome Check
A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backwards as forwards, such as the words madam or racecar, the date/time stamps 11/11/11 11:11 and 02/02/2020, and the sentence: "A man, a plan, a canal – Panama".
Write a JavaScript program to check whether a given string is a palindrome or not using recursion.
Test Data:
("madam") -> true
("abdb") -> false
("ab") -> false
(test("a") -> true
Sample Solution-1:
JavaScript Code:
// Define a function named 'test' that checks if a given string is a palindrome
const test = (text) => {
// Check if the input is not a string
if (typeof text !== 'string') {
return 'String should not be empty!';
}
// Check if the length of the string is less than or equal to 1, it is a palindrome
if (text.length <= 1) {
return true;
}
// Check if the first and last characters of the string are equal
if (text[0] !== text[text.length - 1]) {
return false;
} else {
// Recursively call the 'test' function with the string excluding the first and last characters
return test(text.slice(1, text.length - 1));
}
};
// Test the 'test' function with different input strings
console.log(test("madam")); // Output: true (palindrome)
console.log(test("abdb")); // Output: false (not a palindrome)
console.log(test("ab")); // Output: false (not a palindrome)
console.log(test("a")); // Output: true (palindrome)
Output:
true false false true
Flowchart:
Live Demo:
See the Pen javascript-recursion-function-exercise-10 by w3resource (@w3resource) on CodePen.
Sample Solution-2:
JavaScript Code:
// Function to check if a given string is a palindrome using recursion
function isPalindrome(str) {
// Base case: if the string has 0 or 1 characters, it's a palindrome
if (str.length <= 1) {
return true;
}
// Check if the first and last characters are equal
if (str[0] !== str[str.length - 1]) {
return false;
} else {
// Recursively check the substring excluding the first and last characters
return isPalindrome(str.slice(1, -1));
}
}
// Test the function with different input strings
console.log(isPalindrome("madam")); // Output: true (palindrome)
console.log(isPalindrome("abdb")); // Output: false (not a palindrome)
console.log(isPalindrome("ab")); // Output: false (not a palindrome)
console.log(isPalindrome("a")); // Output: true (palindrome)
Output:
true false false true
Flowchart:
Improve this sample solution and post your code through Disqus.
Previous: Marge sort - recursion.
Next:Convert Binary to Decimal using recursion.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics