如何使用JavaScript检查给定的字符串是否是回文
回文是指一个单词、句子甚至数字从前往后读和从后往前读都一样。因此,如果我们输入一个字符串,反转它并且检查反转后的字符串和原始字符串是否相等,那么这个字符串就是一个回文,否则就不是回文。
方法如下:
- 当用户点击提交按钮时,我们运行一个JavaScript函数。
- 首先将字符串转换为小写。
- 然后我们使用split()方法将字符串拆分成数组,以便可以使用reverse()方法反转。
- 然后我们使用join()方法将数组重新拼接成字符串。
- 最后,我们检查输入字符串和反转后的字符串是否相等。我们将相应更新输出。
示例:
index.html
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: grey;
}
.container {
background-color: #00ffff;
display: flex;
justify-content: center;
align-items: center;
height: 60vh;
width: 80vw;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 25px;
box-shadow: 2px 31px 35px -15px
rgba(0, 0, 0, 0.1);
padding: 10px;
}
.palindrome {
width: 500px;
}
.input-container {
text-align: center;
margin: 30px 0;
}
.btn-container {
text-align: center;
}
input {
width: 70%;
border: none;
padding: 15px;
font-size: 1.1rem;
border-radius: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="palindrome">
<header>
<h1>Palindrome checking using
CSS and JavaScript</h1>
</header>
<div class="main">
<div class="input-container">
<!-- Place to input the string -->
<input type="text" placeholder="Enter...">
</div>
<div class="btn-container">
<!-- Button that will activate the check -->
<button>Check</button>
</div>
<div>
<b>Input String: </b>
<span class="input-string"></span>
<br>
<b>Reversed String: </b>
<span class="reversed-string"></span>
<p class="output-text"></p>
</div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
// Getting the elements from DOM
const btncheck = document.querySelector("button");
const str = document.querySelector("input");
const inputString = document.querySelector(".input-string");
const reverseString = document.querySelector(".reversed-string");
const outputText = document.querySelector(".output-text");
// Adding event listener when the
// user clicks on the "Check" button
btncheck.addEventListener("click", (e) => {
e.preventDefault();
// Converting the input string to smallcase
const input = str.value.toLocaleLowerCase();
// Split the string into an array
const string = input.split("");
// Reversing the array
const rearray = string.reverse();
// Join the array back to a string
const reversedString = rearray.join("");
inputString.textContent = input;
reverseString.textContent = reversedString;
// Checking the input string and
// reversed string if they are the same
if (input == reversedString) {
outputText.textContent =
"The input string is a palindrome!";
} else {
outputText.textContent =
"The input string is not a palindrome";
}
// Reset the input value
str.value = "";
});
输出:

极客教程