检查对提示的响应是否为某个字符串

时间:2018-09-18 13:32:06

标签: javascript

我想检查用户是否输入了字符串,并验证了输入的字符串是否正确。

到目前为止,我已经通过使用提示符()使用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>

1 个答案:

答案 0 :(得分:2)

我相信您需要将提示值分配给变量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>