The code
function palindrome() {
document.getElementById("alert").classList.add("invisible");
//getting the string from user
let msg = document.getElementById("userString").value;
//regular expression
var re = /[^A-Za-z0-9]/g;
//replacing numbers, characters, and spaces
str = msg.toLowerCase().replace(re, '');
var len = str.length;
for (var i = 0; i < len/2; i++) {
if (str[i] !== str[len - 1 - i]) {
document.getElementById(
"msg"
).innerHTML = `Your String is not a palindrome`;
document.getElementById("alert").classList.remove("invisible");
} else{
document.getElementById("msg").innerHTML = `Your String is a palindrome`;
document.getElementById("alert").classList.remove("invisible");
}
}
}
Our code is structured in one function
This function makes use of regular expression in javascript. While checking whether a string is a palindrome or not, we also have to make sure to ignore any spaces, number and special character. That's where regular exoression comes in. In line 8, we intialize that regular expression and in line 11, we replace any special characters with a blank string, essentially removing the characters. We then loop over the string comparing the first character with the last character in a string. That's why our condition in the loop is only valid till half of the string.