The Student Room Group

Java script "Includes"

I was wondering whether there is a way to check if a variable includes something e.g.

if (varX includes "Hello){
console.log "hello";
Reply 1
You can check if a variable is set to null, so

If (varX != null) {
console.log "x"();
}
Reply 2

if (varX.indexOf('Hello') != -1) {
// varX contains Hello
}
Reply 3
Original post by Dez

if (varX.indexOf('Hello') != -1) {
// varX contains Hello
}

I tried this but it did not work
<script>
confirm('Hello!!');
var feeling = prompt('Feel free to talk to me');
if (varfeeling.indexOf('Hello') != -1) {
}
confirm('How are you?');
</script>
(edited 10 years ago)
Reply 4
Original post by SamRob85
I tried this but it did not work
<script>
confirm('Hello!!');
var feeling = prompt('Feel free to talk to me');
if (varfeeling.indexOf('Hello') != -1) {
}
confirm('How are you?');
</script>



Your if statement is empty.
Reply 5
Original post by SamRob85
I tried this but it did not work
<script>
confirm('Hello!!');
var feeling = prompt('Feel free to talk to me');
if (varfeeling.indexOf('Hello') != -1) {
}
confirm('How are you?');
</script>


Replace "varfeeling" with "feeling". var is a keyword used to define a variable, it's not part of the name of that variable.
Reply 6
Original post by Dez
Replace "varfeeling" with "feeling". var is a keyword used to define a variable, it's not part of the name of that variable.

I tried it but it does the same for any input.
Reply 7
Original post by SamRob85
I tried it but it does the same for any input.


I refer you to:

Original post by Damask-
Your if statement is empty.
Reply 8
Original post by Damask-
Your if statement is empty.
What do you mean?
Original post by SamRob85
What do you mean?

Your if statement doesn't contain any code, so regardless of what happens at the if statement the program will do the same thing.
Reply 10
To be explicit, here's what you have:

<script>
confirm('Hello!!');
var feeling = prompt('Feel free to talk to me');

// Check whether input contains hello
if (feeling.indexOf('Hello') != -1) {
// Do absolutely nothing
}

// Show 'How are you?' confirm regardless of what happens
confirm('How are you?');
</script>
Reply 11
Original post by Planto
To be explicit, here's what you have:

<script>
confirm('Hello!!');
var feeling = prompt('Feel free to talk to me');

// Check whether input contains hello
if (feeling.indexOf('Hello') != -1) {
// Do absolutely nothing
}

// Show 'How are you?' confirm regardless of what happens
confirm('How are you?');
</script>

Would moving the confirm('how are you') to the //do absolutely nothing make it work?
Reply 12
Original post by SamRob85
Would moving the confirm('how are you') to the //do absolutely nothing make it work?


Bingo! The 'if' statement means, "if what's in these brackets is true, do what's between the following curly braces." The code outside of those braces runs regardless.
(edited 10 years ago)

Quick Reply

Latest

Trending

Trending