I used Regex and a recursive function because I did not want to repeat the clean-up code for each recursion. I only did it this way simply for the challenge. It is not the simplest way.
function palindrome(str) {
let lowStr = str.toLowerCase();
let symRegExp = /[^a-z0-9]/g; // not alphanumeric characters
let testStr = lowStr.replace(symRegExp, ""); // replace with ""
console.log("Mod Str: ", testStr);
let result = checker(testStr);
return result
}
function checker(str) {
if (str.length < 2){
return "";
}
else {
let test = false;
let head = str.match(/^[a-z0-9]/);
console.log(head[0]);
let tail = str.match(/[a-z0-9]$/);
console.log(tail[0]);
if (head[0] === tail[0]) {
test = true;
}
else {
test = false;
}
console.log(test);
if (str.length <= 2 || test === false) {
console.log("Return: ", test);
return test;
}
else {
let bodyRegex = /(^[a-z0-9])(\w+)([a-z0-9]$)/;
let body = str.replace(bodyRegex, '$2' );
let pal = checker(body);
return (pal === "") ? test : pal;
}
}
}
let resp = palindrome("_A man, a plan, a canal. Panama");
console.log("Result: ", resp);
I wasn’t a fan of regex, but now I’m happy to use it and glad it worked!
function palindrome(str) {
// Remove non-alphanumeric characters by replacing them with an empty string
str = str.toLowerCase().replace(/[^a-z\d]/gi,"");
// Reverse the string
let reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}
Thank you for your answer!
I believe it could be more readable, but once you got what’s going on, it’s easy to get it.
And yeah, you’re right. Isn’t it supposed to be like that? I mean, if I read “m”, it’s the same both forward and backward.
But if you don’t want that to happen, it’s easy to add a if (checkStr.length == 1){return false}, or something similar
Also, I just noticed that it’ll break if the match function on checkStr doesn’t match anything. Because checkStr would be Null, and we can’t .length a null variable.
So, two cases to treat at the beginning of the function :x
I used the spread operator (I think! ) to convert the string to an array, so I could then use .reverse() But I had problems, where I couldn’t refer back to the original, but declared ORIGINAL to keep the pure text. Might be a ‘hacky’ solution, but I got it to work anyway.
// remove all non-alphanumerics & make lowercase
const originalStr = str.replace(/[\W_]/gi, "").toLowerCase();
// KEEP ORIGINAL FOR LATER COMPARISON
const ORIGINAL = originalStr;
// convert originalStr to get reversed version, using spread operator
const originalArray = [...originalStr];
// reverse array in NEW variable to compare
const reverseArray = originalArray.reverse();
// convert back to string
const textToCompare = reverseArray.join("");
// compare
return ORIGINAL == textToCompare;
}
So I had regular expressions stuck in my head and was initially trying to solve the whole thing with just those , but then I watched the video and as soon as Ramón said “loop” I knew what I could do!
function palindrome(str) {
//convert to lowercase, then use regex to replace any non-alpha-numeric characters in that string:
let string = str.toLowerCase();
let justString = string.replace(/[\W_]/gi, "");
//Create new string that reverses the modified string above, using a loop character by character:
let reverseString = "";
for (let i=justString.length-1; i >= 0; i--) {
reverseString += justString[i];
}
// Confirm the reversed string matches the original (returns true or false):
return justString == reverseString;
}
//function to clean string: remove non-alphanumeric characters and make lower case
function cleanAlphaLowercase(str)
{
//convert str to only alphanumeric characters, incl remove spaces & symbols
const regEx = /[\W_]/g;
const alphaStr = str.replace(regEx,'')
//convert str to only lower case characters
const alphaLowerStr = alphaStr.toLowerCase();
return alphaLowerStr;
}
//function to reverse string: using built-in function method, string split, then reverse split
function reverseString(str)
{
const cleanStr = cleanAlphaLowercase(str);
const splitStr = cleanStr.split("");
const reverseArr = splitStr.reverse();
const reversedStr = reverseArr.join("");
return reversedStr;
}
//function that compares clean and reversed strings to check if they're the same. if they are, the string is a palindrome and returns such a message.
function palindrome(str)
{
const forwardStr = cleanAlphaLowercase(str);
const backwardStr = reverseString(str);
console.log('forward: '+forwardStr);
console.log('backward: '+backwardStr);
console.log(`Is '${forwardStr}' equal to '${backwardStr}'?`);
return forwardStr == backwardStr;
}
palindrome(" not a #paLinDRome_");
function palindrome(str) {
let palindromeRegex = /[a-z0-9]/ig; //This regex match only characters and digits
let result = str.match(palindromeRegex); //An array only with characters and digits
let strPal1 = result.join('').toLowerCase();//This concatenates the elements in the array, then converts the string to lowercase
let strPal2 = result.reverse().join('').toLowerCase();//This reverses the elements in the array, concatenates them, and converts them to lowercase.
if (strPal1 == strPal2) {
// if true then it is a palindrome.
return true;
} else {
// if false it is not a palindrome.
return false;
}
};
console.log(palindrome("1 eye for of 1 eye."));
I first created a solution with split and join methods, but here’s a simple one just iterating the array back and for
function palindrome(str) {
//first clean other chars from string
let _cleanStr = str.replace(/[\W_]/ig, "").toLowerCase();
//define matching true unless false
let match = true;
for (let i=0; i < _cleanStr.length; i++){
//iterate _ckeanStr and compare to oposite position of the same string
// this could be simplified to just iterate half of the string
if (_cleanStr[i] !== _cleanStr[_cleanStr.length-1-i]){
match = false
}
}
//return result
return match;
}
palindrome("eye");
function palindrome(str) {
str=str.toLowerCase().match(/[a-z0-9]/g)
//convert the string to lowercase and remove unwanted characters
for(var i=str.length-1; i>=0; i--)
//loop through the string
{ if(str[i]!==str[str.length-1-i])return false}
//if first letter doesn't match the last break out of the loop
//if they match move to the second and second last letter(repeat)
return true}
// if the loop finish return true