I love freeCodeCamp, because it is a great platform to help non-coders get into coding. I’ve actually taken a six month hiatus from coding, and thankfully it was easy to get back into the “Basic Algorithmic Scripting” exercises I have been working through.
Below the exercise asks that we develop a script in Javascript to test if a string is a palindrome, or that basically the string when read in reverse is the same as when read normal order. If so, the algorithm must output true; otherwise it would output false. To make the exercise trickier, our algorithm has to exclude special noncharacter symbols and uppercase letters from the reading of the input string. For example, the string “_Eye” must output a true value, because it would exclude the underscore “_” character and the uppercase E would be ignored.
My solution below:
function palindrome(str) {
var Undercased = str.toLowerCase();
var RemoveCharacters = Undercased.replace(/[^0-9a-zA-Z]/g, ”);
var SplitString = RemoveCharacters.split(”);
var ReversedString = SplitString.reverse();
var JoinedReversed = ReversedString.join(“”);
if (RemoveCharacters == JoinedReversed) {
return true;
}
else {
return false;
}
}
palindrome(“_eye”);
Breakdown:
var Undercased = str.toLowerCase();
First – We create a variable called Undercased that convert each input to a lowercase string just to make sure all upper case letters are ignored.
var RemoveCharacters = Undercased.replace(/[^0-9a-zA-Z]/g, ”);
Second – We take the “Undercased” string, and make sure that each special noncharacter symbols are replaced with a blank.
var SplitString = RemoveCharacters.split(”);
Third – We split the string into an array that is separated by in this case essentially the adjacent letters. For example
“eye” now becomes “e”, “y”, “e”.
var ReversedString = SplitString.reverse();
Fourth – We now take the previous array and reverse the order of the elements
For example, if our last array were (“n”, “o”), it would now become (“o”, “n”).
var JoinedReversed = ReversedString.join(“”);
Fifth, we have to rejoin our strings to see what string is formed. Our array becomes a single string again.
For example “e”, “y”, “e” would become “eye.”
if (RemoveCharacters == JoinedReversed) {
return true;
}
else {
return false;
}
}
palindrome(“_eye”);
Six and Lastly, we want to check to make sure that the initial string after it had the uppercase ignored and special characters ignored matches the latest string that was rejoined. If yes, then the program outputs true; otherwise it outputs false.