kirill2485
kirill2485

Reputation: 377

Create a variable in an IF statement

The code is supposed to take the user to a website, but I don't know how to put variables in an if statement. For example after they type in "Can you go to http://www.google.com", it would go to Google, and if they typed in "Can you go to http://www.yahoo.com" it would go to Yahoo

<script type="text/javascript">
        var question=prompt ("Type in a question");
        if (question==("Can you go to " /*a website*/ )){
            window.location.href = /*the website that the person typed in after to*/;
        }
    }
</script>

Upvotes: 1

Views: 143

Answers (4)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

When you want to match string against a pattern or extract data from it, your best bet in JavaScript is regular expressions. Use String.match to both test if your string fits required pattern and extract the data you need in same check and then use extracted URL in your assignment.

Upvotes: 1

Deestan
Deestan

Reputation: 17136

As Oleg said, use JavaScript's "Regular" Expressions. To illustrate, this is your example made working with a regex:

<script type="text/javascript">
    var question=prompt ("Type in a question");
    var match = /^Can you go to (.*)/.exec(question);
    if (match) {
        window.location.href = match[1];
    }
</script>

Upvotes: 3

neu-rah
neu-rah

Reputation: 1693

you want to parse the string and extract the URL part. Also checking == on the original string will fail because it will contain an url and therefore it wont match. and there is an extra } on that script.

use javascript function .substr(start,length) to work with partial strings, see example at http://www.w3schools.com/jsref/jsref_substr.asp

beware that this compare will be case sensitive, so you might consider using .toUpperCase()

on match use .substr(start) without length to have the rest of the string containing URL

<script type="text/javascript">
    var question=prompt("Type in a question");
    if (question.toUpperCase().substr(0,14)==("CAN YOU GO TO " /*a website*/ )){
        window.location.href = question.substr(14)/*the website that the person typed in after to*/;
    }
</script>

Upvotes: 0

jackJoe
jackJoe

Reputation: 11148

That's not the best approach, since the user could write something else at the prompt, not starting with "Can you go to".

But you can pick the answer of the prompt of which website to go to:

var question = prompt("Which website to go to", "");
//first test if not empty:
if (question != null && question != "") {
    window.location.href = question;
}

Obviously you should test if it is a valid website, etc.

Upvotes: 0

Related Questions