How to write palindrome in JavaScript

前端 未结 30 1767
情书的邮戳
情书的邮戳 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条回答
  •  萌比男神i
    2020-11-29 03:35

    Try this:

    var isPalindrome = function (string) {
        if (string == string.split('').reverse().join('')) {
            alert(string + ' is palindrome.');
        }
        else {
            alert(string + ' is not palindrome.');
        }
    }
    
    document.getElementById('form_id').onsubmit = function() {
       isPalindrome(document.getElementById('your_input').value);
    }
    

    So this script alerts the result, is it palindrome or not. You need to change the your_id with your input id and form_id with your form id to get this work.

    Demo!

提交回复
热议问题