const email = "firstname.lastname@example.org"; const userName = email.substring(0, email.indexOf("@")); console.log(userName); // Outputs "johndoe"
In this example, we define an email address as a string and store it in a variable called
substring() method to extract the part of the string that comes before the “@” symbol. The
substring() method takes two arguments: the starting index and the ending index of the substring. In this case, we start at index 0 and end at the index of the “@” symbol, which is found using the
Finally, we store the user name in a variable called
userName and log it to the console. The result is the string “johndoe”, which is the user name portion of the email address.
Note that this method assumes that the email address is well-formed and contains an “@” symbol. It may not work for all email addresses, especially if they are malformed or contain unexpected characters.