Congrats on solving the palindrome checker project!!
Feel free to drop your solutions here.
Here’s mine:
function cleanUpNonAlpha(str) {
return str.replace(/[\W_]/g, "");
}
function makeUppercase(str) {
return str.toUpperCase();
}
function flipStr(str) {
// Take an empty string
let result = "";
// Start a loop at the end of the input string
// Put the letter at the current stage at the end of the result string
for(let i=str.length-1; i>=0; i--) {
result += str[i];
}
// return result string
return result;
}
function palindrome(str) {
// Clean up string by removing non-alphanumeric characters
const cleanedUpStr = cleanUpNonAlpha(str);
// Make cleaned up string uppercase
const uppercaseStr = makeUppercase(cleanedUpStr);
// Reverse uppercase cleaned up string
const reversedStr = flipStr(uppercaseStr);
// Compare reversed and uppercase string
// If they're the same, it's a palindrome (return true)
console.log(`Is ${uppercaseStr} the same as ${reversedStr}?`)
return reversedStr === uppercaseStr;
}
console.log(palindrome("Tacocat!"));
This is my solution. I have commented out trying to explain it. I hope my english didn’t get too tricky.
Even though my solution seems more fancy, for this challenge an old fashion loop is probably a better aproach. The code is longer but more readeable, readability is really important.
Here it goes:
function palindrome(str) {
// Clean up the string:
// 1 | replace all non alphanumerics characters and underscores from the string using regex (/[\W_]/g)
// and replace method, wich sustitutes all with an empty string
// --> fivefour is the result
// 2 | convert all characthers to lower case
const cleanedUpStr = str.replace(/[\W_]/g, "").toLowerCase();
// Reverse the order of the string letters
// 1 | Convert the cleaned string into an array using the spread operator ([...string])
// --> [ 'f', 'i', 'v', 'e', 'f', 'o', 'u', 'r' ] is the result
// 2 | Reverse the resulting array items using Array.prototype.reverse() method
// --> [ 'r', 'u', 'o', 'f', 'e', 'v', 'i', 'f' ] is the reversed array
// 3 | Join all the items in a single string using Array.prototype.join("") method, no spaces ("", empty string is used)
// --> ruofevif is the resulting reversedStr variable
const reversedStr = [...cleanedUpStr].reverse().join("");
// Console log the obtained variables and too actually see it
console.log({cleanedUpStr}, {reversedStr});
// Return a boolean comparing both variables
return cleanedUpStr === reversedStr;
}
palindrome("five|\_/|four");
That’s my solution - maybe a bit complicated as I haven’t done yesterday’s homework before writing it. I had a bit of a hard time figuring out how to test the arrays for equality (the toString() method), as I forgot that we cannot check the arrays directly for equality.
function palindrome(str) {
//regex to get rid of symbols and make everything uppercase:
let myRegex = /[a-z0-9]/gi;
let strUpper = str.toUpperCase();
strUpper = strUpper.match(myRegex);
//find length of the clean string:
let laenge = strUpper.length;
//reverse the string
let strBackwards = [];
for (let i = 0; i < laenge; i++) {
strBackwards.unshift(strUpper[i]);
}
//as arrays cannot be directly tested for equality, I changed them to strings
if (strUpper.toString() == strBackwards.toString()) {
return true;
} else {
return false;
}
}
console.log(palindrome("1 eye for of 1 eye."))
I did three solutions and this is the shortest one:
function palindrome(str) {
let newStr = str.toLowerCase().replace(/[^a-z\d]/g, "");
return newStr.split("").reverse().join("") === newStr;
}
console.log(palindrome("A man, a plan, a canal. Panama"));
I tend to not introduce new variables when I can reuse them…have to be careful with arrays
My solution:
function palindrome(str) {
str = str.replace(/\W|_/g, ""); //remove non-alphanumeric characters
str = str.toUpperCase(); // all characters to uppercase
for (let i = 0; i <= str.length / 2; i++) {
//compare first letter to last letter etc
if (str[i] !== str[str.length - 1 - i]) {
return false;
}
}
return true;
}
I wanted to do my solution before watching the video so I guess this is not quite as elegant as it could be. I am sure I don’t need \s+ in my variable nospace and I am fairly sure I don’t need to bring the const newPhrase in at all!!
But, what the heck, it works and I think that is what counts - love some of the shortcuts some of you folk have used and I hope we get to learn them soon. But compared to my (also working) solution for Roman Numerals, this is positively glowing with elegance!!!
Cheers folks
Bill
function palindrome(str) {
let nospace = /\s+|\W+|_/gi;
let replace = (str.replace(nospace,""));
const newPhrase = replace.toLowerCase();
for(let i = 0; i < newPhrase.length; i++){
if(newPhrase[i] === newPhrase.charAt(newPhrase.length-i-1)){
}else{
return false;
}
}
return true;
}
palindrome("almostomla")
// removes all non-alphanumeric characters
function cleanUpNonAlpha(str) {
let fixRegex = /\W|_/g; // Change this line
let replaceText = ‘’; // Change this line
return str.replace(fixRegex, replaceText);
}
// reverses string
function reverse(str) {
let result = ‘’;
for (let i = str.length - 1; i >= 0; i–) {
result += str[i];
}
return result;
}
function palindrome(str) {
let strippedStr = cleanUpNonAlpha(str);
// make string lowercase
strippedStr = strippedStr.toLowerCase();
That’s an arrow function with parameters, it was introduced at the beginning von ES6, maybe you forgot it already, and then substituting newStr in the return statement with your definition of newStr.
It’s kinda the same function but less readable.
When you wrote that was your shortest solution, my fingers just started itching to help you changing it into one line
Here’s mine- I was following along with Ramón, so the start is the same, then I paused the lesson and broke away and finished the checker with help from MDN and previous lesson notes.
function cleanUpNonAlpha(str) {
return str.replace(/[\W_]/g, “”);
}
function makeUppercase(str) {
return str.toUpperCase();
}
function flipStr(str) {
return str.split(“”).reverse().join(“”);
}
function palindrome(str) {
const cleanedUpStr = cleanUpNonAlpha(str);
console.log(cleanedUpStr);
const uppercaseStr = makeUppercase(cleanedUpStr);
console.log(uppercaseStr)
const reversedStr = flipStr(uppercaseStr);
console.log(reversedStr);
return uppercaseStr === reversedStr?
true: false;
// If they are the same, it’s a palindrome (return true)
So I did 2 versions. First up a recursive function just because I wanted to practice this.
/*
So, I wanted to have a play writing a recursive function to do this just for the practice.
Even though there is a much simpler way to do it (reversing the string and checking equality).
Recursion logic:
- start with full string e.g. tacocat
- compare first and last characters (= t and t)
- they are a match so a recursive call to same function with substring
excluding these characters - so this case string will be acoca
- and so on until either first and last chars don't match - not palindrome or reach base case
- base case is length of zero or one characters - if this is reached, the string is a palindrome.
*/
function recursiveIsPalindrome(str) {
// if the string has been reduced down to one or no chars, all previous pairs of
// first and last chars match so the string is a palindrome
if (str.length <= 1 ) {
return true;
}
else if (str.charAt(0) === str.charAt(str.length - 1)) {
// if first and last char in string are a match, recursive call of this function with a substring
// excluding these characters.
return recursiveIsPalindrome(str.substring(1, (str.length - 1)));
}
else {
// if characters don't match, definitely not a palindrome, no further checking needed.
return false;
}
}
function palindrome(str) {
// convert string to lower case and strip out all non alphanumeric chars
let testString = str.toLowerCase().replace(/[^a-z0-9]/g, "");
console.log(`Original string = ${str}, stripped string = ${testString}`);
// check if converted string is a palindrome
return recursiveIsPalindrome(testString);
}
console.log(palindrome("eye")); //should return true.
console.log(palindrome("_eye")); //should return true.
console.log(palindrome("race car")); //should return true.
console.log(palindrome("not a palindrome")); //should return false.
console.log(palindrome("A man, a plan, a canal. Panama")); //should return true.
console.log(palindrome("never odd or even")); //should return true.
console.log(palindrome("nope")); //should return false.
console.log(palindrome("almostomla")); //should return false.
console.log(palindrome("My age is 0, 0 si ega ym.")); //should return true.
console.log(palindrome("1 eye for of 1 eye.")); //hould return false.
console.log(palindrome("0_0 (: /-\ :) 0-0")); //should return true.
console.log(palindrome("five|\_/|four")); //should return false.
Second when I started watching the class video and realised just reversing the string was much simpler.
function palindrome(str) {
console.log("Original string: " + str);
// convert string to a single case (all lower)
const lowerCaseStr = str.toLowerCase();
// Clean up string by removing non-alphabetic characters
const cleanedUpString = lowerCaseStr.replace(/[^a-z0-9]/g, "");
console.log("Cleaned up string: " + cleanedUpString);
// reverse string
// Thank you https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/
// then later "Lukas" during the Class Central video session
// for this info on how to reverse a string.
const reversedString = cleanedUpString.split("").reverse().join("");
console.log("Reversed string: " + reversedString);
// compare original cleaned up string and reversed string
// if they match, string is a palindrome
return cleanedUpString === reversedString;
}
console.log(palindrome("eye")); //should return true.
console.log(palindrome("_eye")); //should return true.
console.log(palindrome("race car")); //should return true.
console.log(palindrome("not a palindrome")); //should return false.
console.log(palindrome("A man, a plan, a canal. Panama")); //should return true.
console.log(palindrome("never odd or even")); //should return true.
console.log(palindrome("nope")); //should return false.
console.log(palindrome("almostomla")); //should return false.
console.log(palindrome("My age is 0, 0 si ega ym.")); //should return true.
console.log(palindrome("1 eye for of 1 eye.")); //hould return false.
console.log(palindrome("0_0 (: /-\ :) 0-0")); //should return true.
console.log(palindrome("five|\_/|four")); //should return false.
Only thing I want to point out is that your ternary operator in the return is a bit overboard. Remember that the conditon uppercaseStr === reversedStr already evaluates to either true or false, so no need to make it explicitly. You could do just