How to write palindrome in JavaScript

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

    str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.

    function palindrome(str) {
    
      var str1 = str.toLowerCase().replace(/\s/g, '').replace(
        /[^a-zA-Z 0-9]/gi, "");
    
      var str2 = str.toLowerCase().replace(/\s/g, '').replace(
        /[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");
    
    
      if (str1 === str2) {
        return true;
      }
      return false;
    }
    
    palindrome("almostomla");
    

提交回复
热议问题