Extract the email address from the HTML source code obtained through a GET AJAX request

An interesting scenario arises when the following code is executed from www.example.com. It fetches the complete html source code of www.example.com/example.html and displays it in an alert message.

function process(){
    url = "http://www.example.com/example.html"
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4){
        alert(xhr.responseText)
        }
    }
    xhr.send();
}
process();

Now, the task at hand is to extract an email address from the html source code with a format like this:

<input type="hidden" id="email2" name="email2" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b3aeb7bba6bab396b3aeb7bba6bab3f8b5b9bb">[email protected]</a>" />

If we were on the webpage itself, a simple command such as:

document.getElementById('email2').value

would suffice. However, given the challenge, how can we efficiently parse the email address into a variable using the variable that contains the entire html source code - xhr.responseText?

Answer №1

Unfortunately, you are unable to utilize getElementById as all you possess is a string; however, it is possible to parse it instead.

alert(xhr.responseText.split('id="email2"')[1].split('value="')[1].split('"')[0])

Answer №2

To utilize the xhr call response, you can generate an HTML document and access it through methods like getElementById or other DOM functions.

For guidelines on creating a new HTML document with JavaScript, refer to How to create Document objects with JavaScript.

Answer №3

sample = ""
function handleData(){
    link = "http://www.sampleurl.com/sample.html"
    var request = new XMLHttpRequest();
    request.open("GET", link, true);
    request.onreadystatechange = function() {
    if (request.readyState == 4){
        sample = request.responseText.split('id="email2"')[1].split('value="')[1].split('"')[0]
    proceed();
    //additional actions can be taken here
        }
    }
    request.send();
}
handleData();

function proceed(){
    // additional actions can be taken here as well
    alert(sample);
}

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

How to use React hooks to flip an array

Is it possible to efficiently swap two items in an array using JavaScript? If we are dealing with a boolean, one could achieve this by: const [isTrue, setIsTrue] = useState(false); setIsTrue(!isTrue); However, what if we have an array? // Let's ...

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

Java has trouble decoding non-ASCII characters sent through Ajax

When I send an AJAX request using jQuery post() and serialize, the encoding used is UTF-8. For instance, if 'ś' is input as a name value, JavaScript displays name=%C5%9B. Despite my attempts to set form encoding, it has not been successful. < ...

Can minification of JS be achieved in a Jekyll environment?

Currently, I am in the process of developing a project with Jekyll and one of the requirements is to minify HTML, CSS, and JS. I was wondering if Jekyll has built-in features for JS minification. It may seem like a simple question, but since I am new to ...

When using Vuepress behind a Remote App Server, pages containing iframes may return a 404 error

Creating a static website using Vuepress was a breeze, especially since I included a dedicated section for embedded Tableau dashboards. The website functioned perfectly when accessed online without any issues, displaying the Tableau dashboards flawlessly. ...

Can you explain the role of the %GetOptimizationStatus function within a JavaScript file executing in Node.js?

Currently, I am delving into an article that discusses optimization strategies and includes the following code snippet: //Function that contains the pattern to be inspected (using an `eval` statement) function exampleFunction() { return 3; eval(&a ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

Node js - Looping Through Loading

I am facing an issue with my Node.js application. It runs perfectly fine on my local environment, but when I try to run it on my server using forever, the page just keeps loading without displaying anything. There seems to be no response and it gets stuc ...

Interactive quiz program based on object-oriented principles

As I work on developing a quiz app using JavaScript, everything seems to be going well. However, I've encountered an issue with validation where my code is validating the answers twice - once with the correct answer from the previous question and agai ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchron ...

Ways to extract certain characters from each element in an array

I'm attempting to make the first four characters of each element in an array (specifically a list) bold, but I am only able to select entire strings: $("li").slice(0).css("font-weight", "Bold"); Is there a way for me to indicate which characters wit ...

Attempting to extract the data from SweetAlert

I've been attempting to retrieve the return value from sweetalert, but I encountered this: Promise {<pending>} >__proto_:Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]:true resulting from this piece of code: var ret = swal({ ...

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

When launching JQuery UI Tabs in a new browser tab using ajax, the HTML from the ajax response will be immediately shown

I am currently in the process of upgrading from JQuery UI 1.8.14 to JQuery UI 1.10. Previously, when using v1.8.14 code, opening a tab in a new browser tab would cause the entire page to reload, activating the default tab (tabIndex=0). However, I am faci ...

In the world of Node.js and Java, the concepts of "if"

Here is a code snippet that I am working with: var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; if (randFriend == admin) { //Do something here } else if (randFriend != admin) { client.removeFriend(randFriend); } I am tr ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

What is the best method for circumventing an express middleware?

I am currently working on an express application that utilizes several express routes, such as server.get('*' , ... ) to handle common operations like authentication, validation, and more. These routes also add extra information to the respon ...

An array containing concatenated values should be transferred to the children of the corresponding value

Consider this example with an array: "items": [ { "value": "10", "label": "LIMEIRA", "children": [] }, { "value": "10-3", "label": "RECEBIMENTO", ...

Navigational highlighting of current page section on a one-page website

I'm struggling with adding a navigation bar feature that will highlight the current section being viewed on my website. All I want is for the currently viewed section to appear bold in the navigation bar. Check out the codepen link: HTML <na ...