How to write palindrome in JavaScript

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

    Note: This is case sensitive

    function palindrome(word)
    {
        for(var i=0;i<word.length/2;i++)
            if(word.charAt(i)!=word.charAt(word.length-(i+1)))
                return word+" is Not a Palindrome";
        return word+" is Palindrome";
    }
    

    Here is the fiddle: http://jsfiddle.net/eJx4v/

    0 讨论(0)
  • 2020-11-29 03:19

    Try this

    isPalindrome = (string) => {
        if (string === string.split('').reverse().join('')) {
            console.log('is palindrome');
        }
        else {
            console.log('is not palindrome');
        }
    }
    
    isPalindrome(string)
    
    0 讨论(0)
  • 2020-11-29 03:19

    You could also do something like this :

    function isPalindrome(str) {
    var newStr = '';
    
    for(var i = str.length - 1; i >=0; i--) {
        newStr += str[i];
    }
    
    if(newStr == str) {
        return true;
        return newStr;
    } else {
        return false;
        return newStr;
    }
    }
    
    0 讨论(0)
  • 2020-11-29 03:20

    Frist I valid this word with converting lowercase and removing whitespace and then compare with reverse word within parameter word.

    function isPalindrome(input) {
        const toValid = input.trim("").toLowerCase();
        const reverseWord = toValid.split("").reverse().join("");
        return reverseWord == input.toLowerCase().trim() ? true : false;
    }
    isPalindrome("    madam ");
    //true
    
    0 讨论(0)
  • 2020-11-29 03:21

    25x faster + recursive + non-branching + terse

    function isPalindrome(s,i) {
     return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
    }
    

    See my complete explanation here.

    0 讨论(0)
  • 2020-11-29 03:24
        function palindrome(str) {
            var re = /[^A-Za-z0-9]/g;
            str = str.toLowerCase().replace(re, '');
            var len = str.length;
            for (var i = 0; i < len/2; i++) {
                if (str[i] !== str[len - 1 - i]) {
                    return false;
                }
            }
            return true;
        }
    
    0 讨论(0)
提交回复
热议问题