Hello everyone. I just completed my first JavaScript Algorithms and Data Structures Project and here is the solution:
function palindrome(str) {
// Declare a regex to return only alphanumeric characters
let strRegex = /[A-Za-z0-9]/;
// split the string into an array of individual characters
let splitStr = str.split('').filter((a) => a.match(strRegex)).map((a) => a.toLowerCase());
/* Declare a variable to hold the revised str containing only alphanumeric characters that are not reversed */
let newStr = splitStr.join('');
// Run a for loop to iterate through the splitStr Array
let reversedStr = '';
for (let i = 0; i < newStr.length; i++) {
reversedStr += splitStr.pop();
}
// Check if the newStr is equal to reversedStr.
// if so return true (it is a palindrome)
//else return false (it is not a palindrome)
return newStr === reversedStr;
}
console.log(palindrome("_eye"));
Now I want to understand something. Why is it that when I use this shortened way of representing alphanumeric characters; /\w/ am failing to pass the challenge, but when i use the longer way; /[A-Za-z0-9]/ am passing the challenge?