avatarMonu Kumar Modi

Summary

The provided web content describes a JavaScript function that checks whether a given string is a palindrome, including the process of normalizing the input and iteratively comparing characters from the start and end of the string.

Abstract

The article titled "Coding: Palindromes in JavaScript" explains the implementation of a function named isPalindrome. This function takes a string S as input and determines if it is a palindrome by first converting it to lowercase and removing all non-alphanumeric characters. It then uses two pointers, left and right, to compare characters from both ends of the string, moving towards the center. If any characters do not match, the function logs false to the console; otherwise, it logs true upon completion of the loop. The article concludes by calling the function with the example string 'abda', which is confirmed to be a palindrome, and

Coding: Palindromes in JavaScript

This code defines a function called “isPalindrome” that takes in a single input, “S”, which is the string that will be checked to see if it is a palindrome. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward.

The first step in the function is to convert “S” to lowercase using the “toLocaleLowerCase()” method, and then using the “replace()” method to remove all non-alphanumeric characters by replacing them with an empty string. This is done so that the only characters remaining in the string are letters and numbers, which will make it easier to check if the string is a palindrome.

The function then initializes two variables, “left” and “right”, with the values of 0 and the length of “S” minus 1, respectively. These variables will be used to iterate through the characters of “S” in a while loop, which runs until “left” is no longer less than “right”.

function isPalindrome(S) {
  S = S.toLocaleLowerCase().replace(/[\W_]/g, '') 
  let left = 0
  let right = S.length - 1

  while (left < right) {
    if (S[left] !== S[right]) {
      return console.log(false)
    }
    left++
    right--
  }
  return console.log(true)
}
isPalindrome('abda')

The while loop checks if the character at the current index of “left” is not equal to the character at the current index of “right”. If they are not equal, the function returns “false” by using console.log. If the characters are equal, “left” is incremented and “right” is decremented, and the loop continues.

When the while loop completes, it means that the entire string has been checked and all characters are equal, so the function returns “true” by using console.log.

Finally the function is called by passing “abda” as the input, this will be evaluated as true since ‘abda’ is a palindrome.

Happy learning 😄

Do support our publication by following it

Palindrome
JavaScript
Codin
Data Structures
Interview
Recommended from ReadMedium