1
+ // Write a JavaScript function that checks whether a passed string is palindrome or not?
2
+
3
+ function check_Palindrome ( str_entry ) {
4
+ // Change the string into lower case and remove all non-alphanumeric characters
5
+ var cstr = str_entry . toLowerCase ( ) . replace ( / [ ^ a - z A - Z 0 - 9 ] + / g, '' ) ;
6
+ var ccount = 0 ;
7
+ // Check whether the string is empty or not
8
+ if ( cstr === "" ) {
9
+ console . log ( "Nothing found!" ) ;
10
+ return false ;
11
+ }
12
+ // Check if the length of the string is even or odd
13
+ if ( ( cstr . length ) % 2 === 0 ) {
14
+ ccount = ( cstr . length ) / 2 ;
15
+ } else {
16
+ // If the length of the string is 1 then it becomes a palindrome
17
+ if ( cstr . length === 1 ) {
18
+ console . log ( "Entry is a palindrome." ) ;
19
+ return true ;
20
+ } else {
21
+ // If the length of the string is odd ignore middle character
22
+ ccount = ( cstr . length - 1 ) / 2 ;
23
+ }
24
+ }
25
+ // Loop through to check the first character to the last character and then move next
26
+ for ( var x = 0 ; x < ccount ; x ++ ) {
27
+ // Compare characters and drop them if they do not match
28
+ if ( cstr [ x ] != cstr . slice ( - 1 - x ) [ 0 ] ) {
29
+ console . log ( "Entry is not a palindrome." ) ;
30
+ return false ;
31
+ }
32
+ }
33
+ console . log ( "The entry is a palindrome." ) ;
34
+ return true ;
35
+ }
36
+ check_Palindrome ( 'madam' ) ;
37
+ check_Palindrome ( 'nurses run' ) ;
38
+ check_Palindrome ( 'fox' ) ;
39
+
0 commit comments