编写一个javascript函数来检查一个单词或一个句子是否为回文,不考虑大小写和空格

这是问题陈述。编写一个 javascript 函数来检查一个单词或一个句子是否是回文,而不管大小写和空格。这是我检查回文数的代码,但我不知道如何检查空格。


<html>


<body>

  <script type="text/javascript">

    function checkPalindrome() {

      var revStr = "";

      var str = document.getElementById("str").value;

      var i = str.length;

      for (var j = i; j >= 0; j--) {

        revStr = revStr + str.charAt(j);

      }

      if (str == revStr) {

        alert("The entry is Palindrome");

      } else {

        alert("The entry is not a Palindrome");

      }

    }

  </script>

  <form>


    Enter a String/Number: <input type="text" id="str" name="string" />

    <br />

    <input type="submit" value="Check" onclick="checkPalindrome();" />

  </form>

</body>


</html>


蛊毒传说
浏览 164回答 3
3回答

繁星coding

您可以使用一些内置方法,如String.prototype.split(),Array.prototype.reverse()和Array.prototype.join()反转字符串:function checkPalindrome() {&nbsp; var str = document.getElementById("str").value;&nbsp; var revStr = str.split('').reverse().join('');&nbsp; if(str == revStr) {&nbsp; &nbsp; alert("The entry is Palindrome");&nbsp; }&nbsp;&nbsp;&nbsp; else {&nbsp; &nbsp; alert("The entry is not a Palindrome");&nbsp; }}Enter a String/Number: <input type="text" id="str" name="string" />&nbsp;<br /><input type="submit" value="Check" onclick="checkPalindrome();"/>

隔江千里

在将字符串与反向字符串进行比较时,您可以只使用.equalsIgnoreCase()方法而不是==var str="ma d Am";&nbsp; &nbsp; &nbsp; &nbsp; var revStr="";&nbsp; &nbsp; &nbsp; &nbsp; for(int j=str.length()-1; j>=0; j--) {//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; revStr =(str.charAt(j)==' ')?revStr+" " :revStr+(str.charAt(j));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; revStr = revStr+(str.charAt(j));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(str.equalsIgnoreCase(revStr)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("The entry is Palindrome");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("The entry is not a Palindrome");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

不负相思意

试试function checkPalindrome() {&nbsp; var s=document.getElementById("str").value;&nbsp;&nbsp;&nbsp; var str = s.replace(/ /g, '').toLowerCase();&nbsp; var revStr = [...str].reverse().join``;&nbsp; if (str == revStr) {&nbsp; &nbsp; alert("The entry is Palindrome");&nbsp; } else {&nbsp; &nbsp; alert("The entry is not a Palindrome");&nbsp; }}<form>&nbsp; Enter a String/Number:&nbsp;&nbsp; <input type="text" id="str" name="string" />&nbsp; <br />&nbsp; <input type="submit" value="Check" onclick="checkPalindrome(this);" /></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript