1

I would like to check if the user enters a string and verifying it whether the entered string is right or wrong.

Here I have done so far by using JavaScript by using prompt().

I am successful in displaying the prompt message and when I enter any name, it doesn't show anything. I am unable to get the required output.

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
  • 1
    How is the code not working? Commented Sep 18, 2018 at 13:34

1 Answer 1

3

I believe you need to assign the prompt value to the variable charIn and Hello World to myText.

Also it is better to use includes().

Working Code Example:

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>

Sign up to request clarification or add additional context in comments.

5 Comments

When i am entering the string Hello World, It is showing me the error. Can you help me out with this.
@EdgyAffairs, in that case condition should be if (myText.includes(charIn)){
Thank you for your time
@EdgyAffairs, glad to help. May I request you to accept the answer by clicking on the check mark beside the answer to toggle it from greyed out to filled in.........thanks
Yeah I changed it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.