Check if a String is a palindrome with JavaScript Tutorial

preview_player
Показать описание


Don’t forget to subscribe to the Junior Developer Central channel for more videos and tutorials!

So there are a couple of ways to check is a string is a palindrome in JavaScript and we’ll first look at what seems to be the most logical way of doing it which is using a for loop.

In the tutorial i’ll take you through the process of looping through a string to check if each character at opposite ends of the string are the same.

This process is a pretty simple way to check a string (or number) is a palindrome or not in JavaScript however we’ll look at one problem with this which is if the string has unexpected spaces, commas or other symbols. By definition, as long as the actual letters match up (without any of the symbols) then the string is technically still a palindrome so we should accept it.

So we need a way to remove these characters that we don’t want to check for in our palindrome with JavaScript. You’ll learn a simple way to do this using a Regular Expression.

Once you’ve learnt a way to check for a palindrome using a for loop, we’ll look at some ways of doing it with the javascript reverse function and also a bit of a more esoteric method using a filter function to remove items from the array if they don’t match the end of the string.

Other videos in the JavaScript Snippets series:
Рекомендации по теме
Комментарии
Автор

This was actually very useful! Thank you :)

marykhachatryan
Автор

I didn't think by myself about turn to lower case and removing the non-alphanumerical characters. I did it after watching the video. I used this solution:


const isPalyndrome = (str) => {
str = str.replace(/[^a-z]/gi, "").toLowerCase();
const reverse =
return str === reverse;
}

kremowydzien
Автор

You are amazing. Thank you for your efforts.

nageshthotakura
Автор

Can you do something on how to get odd and even numbers using arrays

Corumt
Автор

Could someone explain the
inStr[inStr.length - 1 - i]
I’m confused on this.

blurrywaters
Автор

I think your first solution was better than the second one

EduardoOviedoBlanco
Автор

i don't understand why - i? and not just[ inStr.length - 1 ]

Girlgirls
Автор

This code doesn't work with strings containing - (hyphen)or _ (underscore) eg "_eye" or "0_0 (: /-\ :) 0-0" ?

selchukkarakus
Автор

Why not use this i++ instead of i+=1 and inStr[inStr.length - 1] instead of this inStr[inStr.length - 1 -i ]

velmurugan.personel