【发布时间】:2020-10-09 02:47:57
【问题描述】:
我只是在做一个反向单词挑战。我有代码并且一切正常我只需要创建一个验证,要求用户输入某种类型的文本。目前,如果您在字段中没有任何文本的情况下单击提交,它仍然会返回它是回文。不确定要在其中添加什么来请求一些文本或告诉用户他们需要输入文本。
document.getElementById("flipBtn").addEventListener("click", function () {
//Here is what happens when the button is clicked.
// Step 1 - Get the Data
let inputWord = document.getElementById("reverseString").value;
// Step 2 - Work with the Data
let lowerInput = inputWord.toLowerCase();
lowerInput = lowerInput.replace(" ", "");
let reverseWord = ""
//First is the Loop Variable followed by a ;.
//Second part is how many times we are looping. Until the second part is false.
//Third is what happens after each loop. ++ means add 1, -- = subtract 1.
//[] indicates array position.
//A string is an array of characters.
//string word = [w][o][r][d]
// 0 1 2 3
//Without the - 1 you get index out of range exception.
//Maybe there is a JavaScript method to make all the letters LowerCase.
//Maybe you want to store four variables, the original input, that reversed, and the lowercase version of each for comparison.
for (let loop = inputWord.length - 1; loop >= 0; loop--) {
reverseWord += lowerInput.charAt(loop);
};
let otherReverse = lowerInput.split("").reverse().join("");
// Step 3 - Output the result
if (lowerInput == reverseWord) {
document.getElementById("reverseOutput").innerHTML = `The word that you entered: ${reverseWord} was changed to: ${otherReverse} is a Palindrome`;
}
else {
document.getElementById("reverseOutput").innerHTML = `The word that you entered: ${reverseWord} was changed to: ${otherReverse} is not a Palindrome`;
}
document.getElementById("reverseString").addEventListener("keydown", function (e) {
var character = (e.which) ? e.which : e.keyCode;
if (character >= 97 && character <= 122 ||
character >= 65 && character <= 90 || character == 8 || character == 9 || character == 32) {
return true;
}
else {
e.preventDefault();
return false;
}
});
})
<div class="container">
<div class="row card"><span class="custfont">Reverse A String</span>
<br />
<div class="col"><input class="input" type="text" id="reverseString" placeholder="Enter your text..." /></div>
<br />
<div class="col"><button class="btn custbtn btn-dark button" id="flipBtn">Flip the String</button></div>
<br />
<div class="col"><span id="reverseOutput"></span></div>
</div>
</div>
【问题讨论】:
标签: javascript reverse palindrome