Write a palindrome program in JavaScript so that only alphanumeric values should be allowed?

JavascriptObject Oriented ProgrammingProgramming

Palindrome

Palindrome is word, a phrase or a number that reads the same backward as forward. For instance Malayalam, madam, nurses run etc.

We should make here the use of a regular expression to allow only alphanumeric characters. "\W" is an inbuilt regex that makes our task easy. There are some steps to follow to check whether a provided string is palindrome or not. 

Steps to follow

  • First we need to change all the characters of a string to lower case.
  • Later we need to remove all non-alphanumeric values. This task can be done by using inbuilt regular expression named '\W' or we can build our own regular expression.
  • we need to replace all the non-alphanumeric values with nothing(""). This task can be done using an inbuilt method called replace().
  • Once we took the non-alphanumeric values from a string, we need to check whether it reads same in backward and forward directions.
  • we need to reverse the refined string using string.reverse() method and the resulted string should be compared with the original string.
  • If both are equal "true" will be displayed in output else "false" will be displayed.

In the following example despite sending non-alphanumeric values such as *, & etc., the program just checks the alphanumeric values and displays the output.  

Example

Live Demo

<html>
<body>
<script>
   function palindrome(str){
   var reg = /[\W_]/g;     // instead of '\W' we also can take "/[^a-zA-Z0-9]+/g"
   var smstr = str.toLowerCase().replace(reg, "");
   var reversed = smstr.split("").reverse().join("");
   if(reversed === smstr){
      document.write("true");
   }
   else {
      document.write("false");
   }
   }
   palindrome("a929a*/(';-=,.*")
</script>
</body>
</html>

Output

true
raja
Published on 11-Jun-2019 14:26:22
Advertisements