In: Computer Science
provide a JavaScript code that finds if the given word by user (prompt) is a Palindrome or no.
Please find the code , inline comments and output below.
<!DOCTYPE html>
<html>
<body>
<script>
function Palindrome_check(str){
// Change the string into lower case and remove all
non-alphanumeric characters from the string
var new_str = str.toLowerCase().replace(/[^a-zA-Z0-9]+/g,'');
var count = 0;
// Check whether the string is empty or not . If empty then return
//false
if(new_str==="") {
return false;
}
// Check if the length of the string is even or odd
if ((new_str.length) % 2 === 0) {
count = (new_str.length) / 2;
} else {
// If the length of the string is 1 then it becomes a
palindrome
if (new_str.length === 1) {
return
true;
} else {
// If the length of the string is odd ignore middle character
count =
(new_str.length - 1) / 2;
}
}
// Loop through to check the first character to the last character
and then move next
for (var i = 0; i < count; i++) {
// Compare characters and drop them if they do not match
if (new_str[i] !=
new_str.slice(-1-i)[0]) {
return
false;
}
}
return true;
}
var word = prompt("Enter the word : ", "");
var result =Palindrome_check(word);
if(result===true){
alert ("The given word is a palindrome");
}
else {
alert ("The given word is not a palindrome");
}
</script>
</body>
</html>
OUTPUT :