Compare forward/backward string

Takes a string as argument, reverses it and checks to see if the string is the same in reverse as it is in its original form.

by David Hughes

JavaScript

// The string
var myStr = "never odd or even";

// Split string into array of characters, even spaces will have a cell in the array.
var strSplit = myStr.split("");
// --> "n", "e", "v"... and so on

//Splice the blank space cells from the array, this makes changes to the original array.
for (var i = strSplit.length - 1; i--;) {
	if (strSplit[i] === " ") strSplit.splice(i, 1);
}

// Convert array back to a string that has no white space. This string can now be compared to the final reversed string.
var noSpaceString = strSplit.join("");




//Reverse the array. And by the time str.Split gets to this part of the program, the blank spaces have been spliced out.
var arrayReverse = strSplit.reverse();
// --> "n", "e", "v"... and so on (should look same as strSplit)

//Join each cell of the array to make a single celled array. Since we are adding no space between the "", this arrayMerge will become a string.
var arrayMerge = strSplit.join("");
// --> neveroddoreven

//Compare the original string to the now reversed string
var compareStrings = function(originalStr, newStr) {
   if (originalStr === newStr) {
       console.log("true");
   }
    else {
        console.log("false");
    }
};


compareStrings(noSpaceString, arrayMerge);