Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 15, 2022 10:30 pm GMT

Palindrome Checker FCC Solution

Before we start, I find it essential you know that Aibohphobia is the fear of palindromes which of course is a palindrome itself, and for all the law suitors out there I'm pretty sure someone with this phobia won't be checking out this article in the first place heheh... ;).

Today we're going to be solving FreeCodeCamp's palindrome checker algorithm the first algorithm in this series. Essentially, we're to return a value of true or false depending on whether the input string is a palindrome or not.

A palindrome is a word that is spelt the same way if read from left to right or from right to left and this is not regarding punctuation marks, spaces or even case.

We can test our algorithm using strings such as "leperS RepEl", "AiboHphobIa", "RaceCar", "rotaTor" and so on. But I will be using "eye" for this example.

We will also be testing for numbers and symbols e.g "2_A3*3#A2" to ensure they aren't being considered when checking for our palindromes.

Here is the piece of code we're given:

function palindrome(str) {  return true;}palindrome("eye");

It is important that we understand what we are working with before we start coding.

So, we're given a string to check if it is a palindrome or not, hence from the definition of a palindrome, we are to determine if the string is the same when read backwards or reversed. Excluding all non-alphanumeric characters and regardless of case.

For my solution, I will first remove all all non-alphanumeric characters and I will use two methods for this which are Regular Expressions otherwise known as REGEX and also using a for loop.

Here is my solution...

function palindrome(str) {  const newStr = str.toLowerCase().replace(/\W|_/g, '');}palindrome("eye");

This is my REGEX approach to removing non-alphanumeric characters

Here, I created a variable newStr which takes in the input from the function which in this case is a string and then runs the toLowerCase() and the replace() methods on it.

The toLowerCase() method is used to turn a string to all lower cased and we do that here to eliminate any case sensitivity issue we might run into as JavaScript is case sensitive. I also used the replace() method which essentially searches for the presence of a character in a given string and then replaces with a provided parameter. Here our replace function takes in a Regular expression /\W|_/g which checks for all instances of non-alphanumeric characters and spaces and it then replaces these characters with an empty string, hence removing them.

I cannot explain REGEX in this post as it is quite complicated to fully understand and is very broad, but the breakdown of the expression is this: The double slashes (//) at the beginning and end of the expression indicates to JavaScript that it is a Regular Expression, the g is something known as a flag in regex which tells JavaScript to check for all the instances of the characters we don't need and not just the first instance of them. The \W checks for everything that is not a letter that is letters, numbers, symbols and even spaces inclusive but for some reason underscores or _ aren't included in this matching so _ was used to check for them.The | stands for or in REGEX to match a string pattern or another which in this case is non-alphanumerics or an underscore.

The next method I will use to filter the string is the string looping approach

function palindrome(str) {  const lettersArr = "abcdefghijklmnopqrstuvwxyz".split('');  const tempStr = str.toLowerCase();  let newStr = ""  for(let i = 0; i < str.length; i++){    if(lettersArr.includes(tempStr[i])){      newStr += tempStr[i]    }  }}palindrome("eye");

Here I created two variables, tempStr and newStr and another variable lettersArr. The lettersArr variable stores all the letters of the alphabet lowercased and then uses the split() method on them. The split method takes a string and splits it into an array with each split located at a the instance of a character that will be provided as a parameter. Here is used "" an empty string so it returns an array consisting of all the letters of the alphabet in lowercase. The tempStr variable converts the input string to lowercase and then stores it. I am going write code to loop over every character of this variable to check for non-alphanumeric characters. The newStr currently has an empty string value but it will store our filtered string.

The for loop runs depending on the length of the original input string and then runs the code it contains for each iteration. Within this for loop, for each iteration the code gets the character in our tempStr that is the same length with the original string, so we get each of its characters individually. I then used the includes() method to check if the character at given index is contained in our alphabets array and if it is, this means it is a letter and it will be added to our newStr variable.

Now we have our filtered string, what next?
I am going to create a variable to store our string in reverse format in order to check if we have a palindrome or not.

Note: I will be using the REGEX approach of filtering the string for the rest of the blog just to make the code a bit more concise.

function palindrome(str) {  const newStr = str.toLowerCase().replace(/\W|_/g, '');  const palinStr = newStr.split('').reverse().join('');}

Here, I created a variable I called palinStr to store the reversed string. This variable takes the filtered string and performs some actions on it so as to reverse it. The split('') method splits the string into an array, I've explained that before in the string filtering code. The reverse() method is an array method that reverses an array. It is a built in JavaScript feature. The join() method joins the elements of an array with a separator that is passed in as a parameter, here I passed in "" so it just combines the array items into one word without any separation or spacing.

I would love to show two methods of reversing the string as well, but just to keep the blog from taking up all the bits in dev.to and taking a bazillion years to read, I won't be doing that. Although if you want me to write a seperate blog on strings and or array methods, you can say that in the comments and I will be sure to do just that.

Now I have my filtered string and also my reversed filtered string. What next?

Finally, I will check if the filtered strings newStr and palinStr are the same and return true or false.

function palindrome(str) {  const newStr = str.toLowerCase().replace(/\W|_/g, '');  const palinStr = newStr.split('').reverse().join('');  return newStr === palinStr}palindrome("eye"); // truepalindrome("leperS RepEl"); // truepalindrome("Hi there"); // falsepalindrome("AiboHphobIa"); // truepalindrome("RaceCar"); // truepalindrome("BobT12_+"); falsepalindrome("rotaTor"); truepalindrome("2_A3*3#A2"); true

Here is the final code:

function palindrome(str) {  const newStr = str.toLowerCase().replace(/\W|_/g, '');  const palinStr = newStr.split('').reverse().join('');  return newStr === palinStr}palindrome("eye");

I will also be making some blogs on regex very soon as it is a very essential and tricky skill to master when learning JavaScript, web development, or just programming in general.

I will be posting more blogs and articles like this so if you found this blog helpful, be sure to obliterate that like button and annihilate the subscribe button. A follow would also be nice btw cos then I get to post more, and you get to learn more, everybody wins!!! Adios amigo, see you on my next post.


Original Link: https://dev.to/michaelx/palindrome-checker-fcc-solution-4j2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To