Reece O'Sullivan Reece O'Sullivan - 1 month ago 14
Javascript Question

JavaScript taking information from a email address

I have been assigned a task at my university to create a web page with two text boxes and a button.

The user is to enter an email address in the format below into the first text box. The user then clicks the button and the surname will appear in the second text box. The email addresses is in the general form

forename.surname@domain.co.uk
.

My function must work for all of the following:


  • Antony.carter@anglia.ac.uk



I have been told to use
.substring()
and
.indexOf()
to find the
surname.

<!DOCTYPE html>
<html>
<head>
<title> JavaScript </title>
<meta name="author" content="Reece">
<meta name="description" content="describe the website">
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<input type="text" id="myText" value=""> </br> </br> <button onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script> function myFunction() { var x = document.getElementById("myText").value; document.getElementById("demo").innerHTML = x; } </script>
</body>
</html>

Answer

First get the email address to parse. You've already done that. Here, x contains the email address.

var x = document.getElementById("myText").value;

Now you can use x.indexOf(".") to get the position of the first period. Likewise, use x.indexOf("@") to get the position of the "@" symbol.

These two values are passed to x.substring() to get the text between the two.

Comments