Palindrome

Problem: Explained

As part of the Javascript Algorithms And Data Structures Certification you need to complete 5 javascript programs, palindrome being one of them. Up next I have quoted the explanation from freeCodeCamp's website.

A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

Note:
You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.

We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR"among others.

We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2".

Solution: At Work


Solution:

Solution: The Code

function palindrome(str) {
    let lowerCaseStr= str.toLowerCase().replace(/[^A-Za-z0-9]/g, '');
    let reverseStr= lowerCaseStr.split('').reverse().join('');
    return lowerCaseStr === reverseStr;
}
                                    

Solution: Step-by-Step

palindrome(_Race Car 5.)

In order to use this function you will need to call it by its name and insert inside of the parentheses the work you want to use it on. For this explanation I will be using the word "_Race Car.".

"_Race Car 5.".toLowerCase

.toLowerCase will return the following: "_race car 5."

"_race car 5.".replace(/[^A-Za-z0-9]/g, '')

"_race car 5.".replace(/[^A-Za-z0-9]/g) will return: "undefinedraceundefinedcarundefined5undefined"

"_race car 5.".replace(/[^A-Za-z0-9]/g, '') will return: "racecar5"

/[^A-Za-z0-9]/ could have been replaced by the other regular expression /[W_]/g. As you may have figured out, this function replaces with nothing '' everything that is not a letter or a number. If we had used '+' as the second argument instead of '' the function would have returned "+race+car+5+".

"racecar5".split('')

"racecar5".split() will return: ["racecar5"]

"racecar5".split('') will return: ["r", "a", "c", "e", "c", "a", "r", "5"]

["r", "a", "c", "e", "c", "a", "r", "5"].reverse()

["r", "a", "c", "e", "c", "a", "r", "5"].reverse() will return ["5", "r", "a", "c", "e", "c", "a", "r"]

["r", "a", "c", "e", "c", "a", "r", "5"].join('')

["r", "a", "c", "e", "c", "a", "r", "5"].join() will return: "r,a,c,e,c,a,r,5"

["r", "a", "c", "e", "c", "a", "r", "5"].join('') will return: "racecar5"

return lowerCaseStr === reverseStr;

=== means strict equality. In javascript, when we are using strict equality between two values it will compare these two. If both values are the same and of the same type, then the boolean true will be returned. Otherwise, false will be returned.