How to write palindrome in JavaScript

前端 未结 30 1764
情书的邮戳
情书的邮戳 2020-11-29 02:42

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad

30条回答
  •  既然无缘
    2020-11-29 03:33

    The code is concise quick fast and understandable.

    TL;DR

    Explanation :

    Here isPalindrome function accepts a str parameter which is typeof string.

    1. If the length of the str param is less than or equal to one it simply returns "false".
    2. If the above case is false then it moves on to the second if statement and checks that if the character at 0 position of the string is same as character at the last place. It does an inequality test between the both.

      str.charAt(0)  // gives us the value of character in string at position 0
      str.slice(-1)  // gives us the value of last character in the string.
      

    If the inequality result is true then it goes ahead and returns false.

    1. If result from the previous statement is false then it recursively calls the isPalindrome(str) function over and over again until the final result.

    	function isPalindrome(str){
    	
    	if (str.length <= 1) return true;
    	if (str.charAt(0) != str.slice(-1)) return false;
    	return isPalindrome(str.substring(1,str.length-1));
    	};
    
    
    document.getElementById('submit').addEventListener('click',function(){
    	var str = prompt('whats the string?');
    	alert(isPalindrome(str))
    });
    
    document.getElementById('ispdrm').onsubmit = function(){alert(isPalindrome(document.getElementById('inputTxt').value));
    }
    
    
    
    

提交回复
热议问题