Palindromes in JavaScript - DEV
Tags: javascript, programming, webdev, coding
Published: 2023-08-28 09:11:21

## Table of Contents 

- <a href=#intro>Introduction</a> 
- <a href="#preq">Prerequisite</a>
- <a href="#what-is-palindrome>What Is a Palindrome</a> 
- <a href="#creating-function">Creating a Palindrome Checker</a> 
    - <a href="#declaring">Declaring the isPalindrome Function</a>
    - <a href="#defining">Defining the Function Parameters</a>
    - <a href="#prepare">Preparing the String</a> 
    - <a href="#reverse">Reversing the Word</a> 
    - <a href="#compare">Comparing the Two Strings</a> 
- <a href="#solve">Solving Real Challenges</a> 
    - <a href="#challenge-1">Challenge 1: Sentence Palindromes</a> 
        - <a href="#problem-1">Problem: Detecting Palindromes in Sentences</a> 
        - <a href="#solution-1">Solution: isSentencePalindrome Function</a> 
    - <a href="#challenge-2">Challenge 2: Word Palindromes</a> 
        - <a href="problem-2">Problem: Identifying Palindromic Words</a> 
        - <a href="#solution-2">Solution: findWordPalindromes Function</a> 
    - <a href="#challenge-3">Challenge 3: Longest Palindromic Substring</a> 
        - <a href="#problem-3">Problem: Finding the Longest Palindromic Substring</a>
        - <a href="#challenge-3">Solution: findLongestPalindromicSubstring Function</a>
- <a href="#conclusion">Conclusion</a>

<h2 id="intro">Introduction</h2>

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. 

<h2 id="preq">Prerequisite</h2>

- 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](https://www.freecodecamp.org/news/regular-expressions-for-beginners/) 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](https://www.freecodecamp.org/news/the-javascript-array-handbook/) 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. 


<h2 id="what-is-palindrome">What is palindrome</h2>

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.
 
<h2 id="creating-function">Creating a palindrome checker</h2> 

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.
 
<h3 id="declaring">Declaring the function</h3>
 
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. 

```js
function isPalindrome() {

}
```

<h3 id="defining">Defining the function parameters</h3>

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

```js
function isPalindrome(input) {

}
```
 
<h3 id="prepare">Preparing the string</h3>

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`. 

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

<h3 id="reverse">Reversing the word</h3>

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.

```js
function isPalindrome(input) {
  const preparedString = input.replace(/[^A-Za-z0-9]/g, '');
  const reversedString = preparedString.split('').reverse().join('');
}
```
 
<h3 id="compare">Comparing the two strings</h3>

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. 


```js
function isPalindrome(input) {
  const preparedString = input.replace(/[^A-Za-z0-9]/g, '');
  const reversedString = preparedString.split('').reverse().join('');
  return reversedString === preparedString;
}
```
 
<h2 id="solve">Solving real challenges</h2> 

In this section, you’re going to use the `isPalindrome` function created earlier in this article to solve the following challenges on palindromes.
 
<h3 id="challenge-1">Sentence palindrome</h3>

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. 

<h4 id="problem-1">Problem<>

You’re given a sentence. Check whether the sentence is a palindrome or not.
 
<h4 id="solution-1">Solution</h4>

```js
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.");
}
```

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.
```
 

<h3 id="challenge-2">Word palindrome</h3>

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.

<h4 id="problem-2">Problem</h4>

You’re given a sentence. Find the words that are palindromes within the given sentence.
 
<h4 id="solution-2">Solution</h4>

```js
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);
```

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' ]

```
<h3 id="challenge-3">Longest palindromic substring</h3>

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

<h4 id="problem-3">Problem</h4>

You’re given a sentence. Find the longest palindromic substring within the sentence.
 
<h4 id="solution-3">Solution</h4>

```js
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);
```

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
```

<h2 id="conclusion">Conclusion</h2>

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: 

- [LinkedIn] (linkedin.com/in/derajs) 
- [Twitter] (twitter.com/chideracode)