DEV Community

Cover image for Palindromes in JavaScript - DEV
Chidera Humphrey
Chidera Humphrey

Posted on • Updated on

Palindromes in JavaScript - DEV

Table of Contents

Introduction

In the world of coding challenges, palindromes are like captivating puzzles. They test how well you can work with words in JavaScript.

In this article, you'll learn:

  • What exactly a palindrome is.
  • How to use JavaScript to solve these word puzzles.

Let’s dive in.

Prerequisite

  • Basic understanding of JavaScript fundamentals, including variables and data types.
  • Proficiency in creating and using functions in JavaScript.
  • Familiarity with regular expressions (RegEx) in JavaScript. If you’re not familiar with regular expressions, this article might be helpful.
  • Knowledge of essential JavaScript array methods like split(), join(), and reverse(). If you’re not familiar with these array methods, this article might be helpful.
  • Access to a code editor or integrated development environment (IDE) for writing and testing your JavaScript code. If you’re coding from your Android/iOS, I recommend using the JS Run app.

What is palindrome

In the coding world, a palindrome is a word or phrase that reads the same way forwards and backwards. For example, 'radar' and 'level' are palindromes. They're like word puzzles with a unique twist.

Now, let's dive into how you can solve these word games using JavaScript.

Creating a palindrome checker

In this section, you are going to learn how to create a JavaScript function that checks whether a string is a palindrome or not. This will be the fundamental block for solving palindrome challenges.

Declaring the function

Start by declaring a function. Let’s call it isPalindrome ; you can call it any thing you want, but make sure it’s descriptive enough.

function isPalindrome() {

}
Enter fullscreen mode Exit fullscreen mode

Defining the function parameters

The isPalindrome will take only one parameter—input string you want to check for being a palindrome.

function isPalindrome(input) {

}
Enter fullscreen mode Exit fullscreen mode

Preparing the string

Depending on the challenge, the input string might contain special characters (characters that are neither an alphabet nor a number). In that case, you want to remove the special characters.

To achieve this, use replace() and regular expression to replace the special characters with an empty string.

The resulting string is stored in the variable, preparedString.

function isPalindrome(input) {
  const preparedString = input.replace(/[^A-Za-z0-9]/g, '');
}
Enter fullscreen mode Exit fullscreen mode

Reversing the word

  1. Use the split() method to convert preparedString into an array.
  2. Store the resulting array in a variable, reversedString. We’re using reversedString as the variable because the array will be converted back to a string.
  3. Reverse the order of arrangement of the array using the reverse() method.
  4. Use the join() method to convert the array back to a string.

Note that all these steps are done in a single statement.

function isPalindrome(input) {
  const preparedString = input.replace(/[^A-Za-z0-9]/g, '');
  const reversedString = preparedString.split('').reverse().join('');
}
Enter fullscreen mode Exit fullscreen mode

Comparing the two strings

Use the strict equality operator, ===, to compare reversedString and preparedString. If they match, the input string is a palindrome.
Use the return statement to return true or false depending whether the input string is a palindrome or not.

function isPalindrome(input) {
  const preparedString = input.replace(/[^A-Za-z0-9]/g, '');
  const reversedString = preparedString.split('').reverse().join('');
  return reversedString === preparedString;
}
Enter fullscreen mode Exit fullscreen mode

Solving real challenges

In this section, you’re going to use the isPalindrome function created earlier in this article to solve the following challenges on palindromes.

Sentence palindrome

One of the fundamental challenges involving palindromes is determining whether a sentence is a palindrome or not. This task requires considering not only the characters but the spaces, punctuation, and case-insensitivity.

Problem<> You’re given a sentence. Check whether the sentence is a palindrome or not.

Solution

function isSentencePalindrome(sentence) {
  // Prepare the sentence (remove spaces, punctuation, and make it lowercase).
  const preparedSentence = sentence.replace(/[^A-Za-z0-9]/g, '').toLowerCase();

  // Use the isPalindrome function to check if the prepared sentence is a palindrome.
  return isPalindrome(preparedSentence);
}

const sentence = "Was it a car or a cat I saw?";
const result = isSentencePalindrome(sentence);

if (result) {
  console.log("The sentence is a palindrome.");
} else {
  console.log("The sentence is not a palindrome.");
}
Enter fullscreen mode Exit fullscreen mode

In this example, the code prepares the sentence by converting it to lowercase. It then checks if the prepared sentence is a palindrome and informs the user of the result.

When you run this code with the provided sentence, it will output:

The sentence is a palindrome.
Enter fullscreen mode Exit fullscreen mode

Word palindrome

Building on your knowledge of palindrome checking, the next challenge is to determine if individual words within a sentence are palindromes. Unlike sentence palindromes, where you consider the entire sentence, word palindromes focus on individual words in the sentence.

Problem

You’re given a sentence. Find the words that are palindromes within the given sentence.

Solution

function findWordPalindromes(sentence) {
  // Split the sentence into words.
  const words = sentence.split(' ');

  // Initialize an array to store word palindromes.
  const wordPalindromes = [];

  // Iterate through each word.
  words.forEach((word) => {
    // Prepare the word (remove spaces, punctuation, and make it lowercase).
    const preparedWord = word.replace(/[^A-Za-z0-9]/g, '').toLowerCase();

    // Use the isPalindrome function to check if the prepared word is a palindrome.
    if (isPalindrome(preparedWord)) {
      wordPalindromes.push(word);
    }
  });

  return wordPalindromes;
}

const sentence = "A man a plan a canal Panama";
const wordPalindromes = findWordPalindromes(sentence);

console.log("Word Palindromes:", wordPalindromes);
Enter fullscreen mode Exit fullscreen mode

In this example, the code:

  1. splits the sentence into words,
  2. prepares each word by removing spaces and punctuation,
  3. checks if each word is a palindrome,
  4. and stores the word palindromes in an array.

Finally, it outputs the word palindromes found in the input sentence.

When you run this code with the provided sentence, it will output:

Word Palindromes: [ 'A', 'a', 'plan', 'a', 'Panama' ]

Enter fullscreen mode Exit fullscreen mode

Longest palindromic substring

Increasing the complexity, the next challenge is to find the longest palindromic substring in a text.

Problem

You’re given a sentence. Find the longest palindromic substring within the sentence.

Solution

function findLongestPalindromicSubstring(text) {
  let longest = ''; // Initialize a variable to store the longest palindrome found.

  // Outer loop iterates over the text character by character.
  for (let i = 0; i < text.length; i++) {
    // Inner loop iterates from the current character to the end of the text.
    for (let j = i + 1; j <= text.length; j++) {
      // Extract the current substring from the text.
      const substring = text.slice(i, j);

      // Check if the substring is a palindrome using the isPalindrome function.
      if (isPalindrome(substring) && substring.length > longest.length) {
        // If it's a palindrome and longer than the current longest, update longest.
        longest = substring;
      }
    }
  }

  // Return the longest palindromic substring found.
  return longest;
}

// Input text to be analyzed.
const text = "racecarbananaappledeifiedlevel";

// Call the findLongestPalindromicSubstring function.
const longestPalindrome = findLongestPalindromicSubstring(text);

// Output the result.
console.log("Longest Palindromic Substring:", longestPalindrome);
Enter fullscreen mode Exit fullscreen mode

In this example, the findLongestPalindromicSubstring function iterates through the text, checking each possible substring for palindromes using the isPalindrome function. It keeps track of the longest palindromic substring found and returns it.

When you run this code with the provided text, it will output:

Longest Palindromic Substring: deified
Enter fullscreen mode Exit fullscreen mode

Conclusion

From understanding the basics to crafting efficient palindrome-checking functions, you've gained valuable knowledge of string manipulation and problem-solving. Throughout this journey, you've honed your skills by:

  • Learning the intricacies of palindrome patterns.
  • Creating JavaScript functions to detect palindromes.
  • Harnessing the power of regular expressions.
  • Employing essential array methods for string manipulation.
  • Tackling real challenges, from sentence palindromes to word palindromes.

Remember, palindromes are not just fun puzzles; they reflect the elegance of problem-solving in coding. These skills will serve you well in tackling a wide range of challenges as a programmer.

Now, it's your turn to put your knowledge to the test! Try creating your own palindrome-checking functions, exploring more complex challenges, or even contributing to open-source projects.

I’d love to hear your thoughts on this article. Did you find it helpful? Do you have any questions or suggestions for future tutorials?

Please share your feedback and insights in the comments section below.

Your input can help me tailor future content to your interests and needs.

P.S. Stay Connected! For more coding tips, tutorials, and updates, be sure to connect with me on LinkedIn and Twitter. We're excited to continue this coding journey with you:

Top comments (0)