/Here is way much simpler code for the palindrome checker. I have written the code in step by step manner to explain what I did here/
function palindrome(str){
var revArr=[]
//console.log(str)
//removing all the dot , comma , whitespace(/\s/g) , dash from the string
str = str.toLowerCase().replace(/[.,\s_-\W]/g,"")
//console.log(str)
//converting string into array using the ... method
str = [...str]
//console.log(str)
//for loop for reversing the original string array and saving it into revArr
for(var i=0;i<str.length;i++){
revArr.unshift(str[i])
}
//console.log(revArr)
//converting revArr (Array) into string
var revStr = revArr.join("")
str = str.join("")
//console.log(revStr,str)
//Moment of truth
if(str === revStr){
//console.log(true)
return true
}
else{
//console.log(false)
return false
}
}
For future reference, when you want to paste code into this forum you need to wrap it in triple backticks (three backticks, new line, your code, new line, three backticks).
Your code is pretty similar to Solution 1 in the hints. I think the solution code might be considered simpler by some because it takes advantage of method chaining and doesn’t need to declare a second array. You could also make yours more concise by getting rid of the if/else at the end and just have:
return str === revStr;
But simplicity is sometimes in the eye of the beholder and more concise doesn’t always mean easier to understand.
I have added spoiler tags to your code for those who have not worked on this problem yet.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
I agree with you. Thanks for your valuable feedback and tips. I am still new at JS, so the code is not as good as the solution already posted by others. But hopefully, with practice, I will learn to write more cleaner code.