Skip to content
the poor coder

palindrome string

Poor Man
Published
Reading time
1 min read
On this page

Palindrome String#

A palindrome string is a string that reads the same forwards and backwards. For example, "racecar" is a palindrome string because it reads the same way both forwards and backwards.

There are several ways to check if a string is a palindrome:

Method 1: Using a loop#

Text

function isPalindrome(str) {
  for (let i = 0; i < str.length / 2; i++) {
    if (str[i] !== str[str.length - 1 - i]) {
      return false;
    }
  }
  return true;
}

console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false

This method uses a loop to iterate through the string and check if the characters at the beginning and end of the string are the same. If they are not the same, the function returns false. If the loop completes without returning false, it means the string is a palindrome and the function returns true.

Method 2: Using the reverse method#

Text

function isPalindrome(str) {
  const reversedStr = str.split("").reverse().join("");
  return str === reversedStr;
}

console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false

This method uses the reverse method to reverse the string and then compares it to the original string. If they are the same, the function returns true, otherwise it returns false.

Both methods work equally well, but the second method is shorter and more concise. However, it may not be as efficient as the first method since it creates a new string by reversing the original string.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC