0

I wanted to do something in my code that if this text was equal to the text I wanted, do it, and if it was not equal, do it. Now what should I define to check if the text is the same as the text I want? As below.

function email(){
    let email = prompt('Enter your email!');
    let gmail = "@gmail.com";
    if (/* 
        Now I want to go here and check if the text has the "gmail" variable or not.
         */
        ) {
        alert('Successfully!. and your email is' + email);
    } else { 
        alert("I'm sorry. This email address is incorrect.")
    };
};
  • I think you're trying to check if `@gmail.com` is in `email` right? Not if it's exactly the same? In this case you can use `email.includes( gmail )` or to check if `email` ends with `gmail` : `email.endsWith(gmail)` – Getter Jetter Jun 18 '21 at 10:47

2 Answers2

1

You could do with String.includes

function email(){
    let email = prompt('Enter your email!');
    let gmail = "@gmail.com";
    if (email.includes(gmail)) {
        alert('Successfully!. and your email is' + email);
    } else { 
        alert("I'm sorry. This email address is incorrect.")
    };
};

email()
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

You can do the following.

if(email.includes(gmail))
{
   //do something here
}

For more info check: How to check whether a string contains a substring in JavaScript?