How to write palindrome in JavaScript

前端 未结 30 1792
情书的邮戳
情书的邮戳 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:44

    Use something like this

    function isPalindrome(s) {
        return s == s.split("").reverse().join("") ? true : false;
    }
    
    alert(isPalindrome("noon"));
    

    alternatively the above code can be optimized as [updated after rightfold's comment]

    function isPalindrome(s) {
        return s == s.split("").reverse().join("");
    }
    
    alert(isPalindrome("malayalam")); 
    alert(isPalindrome("english")); 
    

提交回复
热议问题