简体   繁体   English

检查最后一个字符是否是JavaScript中的问号

[英]Check if last character is a question mark in javascript

  function askQuestion(){ var Prompt = prompt("What yes or no question do you have?", "Type it here..."); var number = Math.floor((Math.random() * 8) + 1); if(Prompt != null){ if (number == 1){ alert("Signs point yo yes."); }else if(number == 2){ alert("Yes."); }else if(number == 3){ alert("Reply hazy, try agian."); }else if(number == 4){ alert("Doubtful."); }else if(number == 5){ alert("All signs point to no."); }else if(number == 6){ alert("Most Likely."); }else if(number == 7){ alert("Absolutely."); }else if(number == 8){ alert("It doesn't look good."); } }else{ alert("Please re-ask the Magic 8 Ball.") } } 
  <body bgColor="Black"> <center><img src="8ball.png" onClick="askQuestion()" style="cursor:pointer;"></center> </body> 

This is what I have. 这就是我所拥有的。 What I would like to know, is how to see the text typed in the prompt has a question mark at the end. 我想知道的是,如何查看提示中键入的文本在末尾带有问号。

if Prompt is a string then it should just be as simple as 如果Prompt是一个字符串,那么它应该像

var lastChar = Prompt.slice(-1);
if(lastChar == '?') { .... }
if (Prompt.slice(-1) === "?") { ... }
var lastChar = (Prompt.trim().substr(-1) === '?')

You can use the charAt() method: 您可以使用charAt()方法:

var lastChar = Prompt.charAt(Prompt.length-1);
if (lastChar === "?") {
    // your logic here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM