首页 > 解决方案 > 检查对提示的响应是否为某个字符串

问题描述

我想检查用户是否输入了一个字符串并验证输入的字符串是对还是错。

到目前为止,我已经通过使用 prompt() 来使用 JavaScript。

我成功显示了提示消息,当我输入任何名称时,它什么都不显示。我无法获得所需的输出。

function myFunction() {
  var myText = prompt("Hello World");
  var response;

  if (myText.search(charIn) > 0) {

    response = "Yes, that letter is in the string";

  } else {

    response = "No good, that letter is NOT in the string";
  }
  document.getElementById("demo").innerHTML = response;

}
<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

标签: javascript

解决方案


我相信您需要将提示值分配给变量charIn并将Hello World分配给myText.

另外最好用includes()

工作代码示例:

function myFunction() {
  var myText = 'Hello World'
  var charIn = prompt();
  var response;

  if (myText.includes(charIn)){
    response = "Yes, that letter is in the string";
  }else{    
    response = "No good, that letter is NOT in the string";
  }
    document.getElementById("demo").innerHTML = response;
}  
   
myFunction();
<span id="demo"></span>


推荐阅读