Check if last character is a question mark in javascript - Stack Overflow

function askQuestion(){var Prompt = prompt("What yes or no question do you have?", "Type

	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>

	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.

Share asked Nov 6, 2015 at 20:36 Headless DevHeadless Dev 991 silver badge12 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

if Prompt is a string then it should just be as simple as

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

Old answer (substr()):

var lastChar = (Prompt.trim().substr(-1) === '?')

New answer (substring()):

var lastChar = (Prompt.trim().substring(Prompt.length - 1) === '?')

You can use the charAt() method:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744855934a4597404.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信