java script loop - how to save index values

Planning to create a program that extracts the domain from an email address. How can this be done without using built-in functions like .map .filter .reduce .split .join .indexOf .findIndex .substring? Many online sources suggest using a for loop to locate "@" and "." symbols, but how do you extract the string between these two markers as the output?

For example: Input = [email protected] Output = gmail

 Input = <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f4f2e9f0ece5b2c0f9e1e8efefaee3efed">[email protected]</a>
 Output = yahoo

let input = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5889c87809691a58288848c89cb868a88">[email protected]</a>"
let output = ""
let begin = ""
let end = ""

for (let i = 12; i<input.length; i++){
    if(input[i] == "@"){
        begin += input[i+1]
    }
}

for (let j = 0; j<input.length; j++){
    if(input[j] == "."){
        end += input[j-1]
    }
}

Answer №1

function extractEmail() {

let input = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac7d3c8cfd9deeacdc7cbc3c684c9c5c7">[email protected]</a>"
let output = []
let didReachAtSymbol = false

for (let i = 0; i < input.length; i++) {
    if(input[i] == "@") {
       didReachAtSymbol = true
    } else if(input[i] == '.'){
       break
    } else if(didReachAtSymbol) {
       output.push(input[i])
    }
}

return output.join('')
}

console.log(extractEmail())

The main idea revolves around starting to add characters to the output once an @ symbol is encountered, and then stopping when a . is found. Upon encountering a ., the function breaks and returns the extracted value.

Answer №2

const email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35692c282e383b0f2c262a2227612c232f">[email protected]</a>"

let startIdx = null
let endIdx = null

for (let i = 0; i < email.length; i++) {
    if (email[i] === '@') {
        startIdx = i + 1
    } else if (email[i] === '.') {
        endIdx = i + 1
        break
    }
}

let domain = email.substring(startIdx, endIdx)

This code provides a basic solution for extracting the domain from an email address, though it may not handle all potential errors smoothly.

Answer №3

It seems like you've dabbled in JavaScript which is a great start! Enhance your learning experience with code snippets like the following:

var input = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bacec8d3cad6df88fac3dbd2d5d594d9d5d7">[email protected]</a>"
var domainWithoutCom = input.split('@')[1].split('.')[0]
console.log(domainWithoutCom)

split function comes in handy for tasks like this!

EDIT:

I apologize for any confusion. Here's an alternate version for you to review my solution :)

Take a look at this improved snippet, it may give you some valuable insights :)

var email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2645474a504f48084853484355665f474e49490845494b">[email protected]</a>';
var count = 0;
var domain = '';
var findFirst = false;
var searching = true;
do {
    var char = email[count];
    if (findFirst) {
        if (char == '.') {
            searching = false;
        } else {
            domain += char;
        }
    }
    else {
        if (char == '@') {
            findFirst = true;
        }
    }
    count += 1;
} while (searching == true);

console.log(domain)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing React callback refs from exposing class methods externally

In the task at hand, I am required to create a React component for displaying toasts that hide by themselves and show from outside. Most guides on React focus on how to access the DOM from a React component, but there is little information available on how ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

The accordion feature fails to function properly when incorporated into an ajax response

When I click a button, an Ajax response is loaded. The response is successfully appended where it should be, but the issue arises with the accordion not working for the response part. Below is the structure of my response: <div class="articles-content ...

In the event of a 404 error, simply direct the user to the pageNotFound before ultimately guiding them back

I'm developing a website with Node JS and I want to implement a feature where if the user attempts to navigate to a non-existent page, they are redirected to a "Page Not Found" message before being automatically taken back to the home page after a few ...

Encountering an error stating "Potential null object" while attempting to retrieve the total count of characters and numbers in a given string

Currently, I am trying to find the number of characters and digits that repeat more than once in a given input string. For example, if the input is "zzrrcde", the output should be 2 as both z and r occur more than once. Here is the function I have writte ...

Tips for converting a URL to the correct route in emberjs when the location type is set to history

After creating a basic Ember.js application and setting the router location type to 'history', I encountered an issue with the generated URLs. Instead of the expected URL format like http://localhost/#/post/1, the Ember.js application was changi ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

Is it possible to analyze an API call and determine the frequency of a specific field?

Code: var textArray = new Array(); var allText = results.data._contained.text; for (var i = 0; i < allText.length; i++) { var text1 = allText[i]; var textHtml = "<div id='text_item'>"; textHtml += "& ...

On button click, Jquery scans for every occurrence of a specified class and then eliminates an extra class associated with them

Apologies if the title is unclear, I am still learning Javascript and Jquery which sometimes makes it challenging to phrase questions correctly. Here's the scenario: I have numerous divs all labeled with a class of thumbnail: <div class="thumbna ...

Transferring data between two "Data" elements using Jquery Datatable

Utilizing the JQuery datatable, I have made the first column of my table clickable, which is labeled as RequestNo. Here's the code snippet: "ajax": { "url": "/Request/Search/LoadData", "type": "POST", "datatype": "j ...

The utilization of TemplateUrl proves to be ineffective

Hello, I am experiencing an issue with my code. When I click on a link, the page does not reload. Below is the HTML and JS code: var app=angular.module('mainApp',['ngRoute']); app.config(function($routeProvider){ $routeProvide ...

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

Attempting to grasp the intricacies of the express Router functionality

I'm a beginner with Node.js and I currently have three JS files: The Index.js file has the following code: var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, r ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Discovering a way to showcase every event a user is linked to, employing Fullcalendar Rails

Here is the current model structure: class User < ActiveRecord::Base has_and_belongs_to_many :event_series has_many :events, through: :event_series end class Event < ActiveRecord::Base belongs_to :event_series end class EventSeries < Activ ...

Is there a better alternative to using for-loops for comparing rasters in R?

Looking for an efficient way to compare pairs of distribution rasters (raster layers with 0 and 1 values). The goal is to measure the similarity among approximately 6500 global rasters using Istat from the SDMTools package. Below is the code snippet: lib ...

What is the best way to ensure that an array containing hex colors is accurate and filter out any incorrect values?

I am currently only checking if values are not null or undefined, but I want to ensure that each hex color is correct. If a hex color is incorrect, I need to discard it and move on to the next one. If the format is completely wrong, then I should reset to ...

Injecting styles dynamically with Nuxt: A step-by-step guide

During the development of a Nuxt application integrated with WordPress, I encountered an issue while trying to import custom CSS from the WordPress API. I am seeking guidance on how to incorporate custom CSS into a template effectively? <template> ...

Navigate to a different webpage: Node.js

I've tried numerous solutions listed here, but being new to node.js, I seem to be missing a crucial part in my code. Can someone please assist me in identifying and resolving the issue? When the login button is clicked, my objective is to redirect the ...