如何使用 JavaScript 检查给定的字符串是否为回文?
回文是一个单词、句子或偶数,从后面和前面读起来都是一样的。因此,如果我们取输入,反转字符串,并检查反转后的字符串和原始字符串是否相等,这意味着该字符串是回文,否则,它不是。
方法:
- 当用户点击提交按钮时,我们运行一个 JavaScript函数。
- 我们首先将字符串转换为小写。
- 然后我们使用split() 方法将字符串拆分为一个数组,以便可以使用reverse() 方法对其进行反转。
- 然后,我们使用join() 方法将数组连接回字符串。
- 最后,我们检查输入字符串和反转字符串是否相等。我们将相应地更新输出。
例子:
index.html
Palindrome checking using
CSS and JavaScript
Input String:
Reversed String:
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 pallindrome!";
} else {
outputText.textContent =
"The input string is not a pallindrome";
}
// Reset the input value
str.value = "";
});
脚本.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 pallindrome!";
} else {
outputText.textContent =
"The input string is not a pallindrome";
}
// Reset the input value
str.value = "";
});
输出: