Using Javascript and the Document Object Model (DOM) to parse a Key/Value

When a server sends a string to the Firefox Browser, it is in the following format:

"KEY:a1 VAL:123.45"

This string can consist of multiple records like this.

Below is the code I wrote to handle this information:

    var e;
    var reply = request.responseText;
    var txt = "", tab, key = "", val = "";
    var x = reply.getElementsByTagName("KEY:");
    for(i = 0; i < x.length; i++)
    {
        txt = x[i].childNodes[0].nodeValue; // "KEY:%c%c VAL:%.2F"
        tab = txt.split(":");
        key = "table_" + tab[1].substring(0,1);
        val = tab[2];
        e = document.getElementById(key);
        e.innerHTML = val;
        e.style.display = "block";
    }

The val variable currently displays "KEY:a1 VAL:123.45" instead of just "123.45" as expected. Additionally, the key variable doesn't match a table cell correctly, only selecting the first one available.

I am struggling with displaying the values of key and val, as using functions like document.write() or alert() don't seem to work for me in Firefox. I'm finding it challenging to trace this code.

If you have any ideas, tips, corrections, or examples of code to share, I would appreciate it. However, please refrain from suggesting libraries, as I aim to achieve this with minimal code.

UPDATE: After reading the comments, I realize there are two approaches to tackle this issue: either by utilizing DOM objects and HTML tags or working with 'strings'. My preference is to stick to the current format, so any guidance towards a 'string' solution would be helpful. Thank you!

Answer №1

To extract the necessary information from a given string, you can employ a straightforward regular expression:

let data = "LABEL:alpha DATA:678.90"​,
    regex = /LABEL:(\S+) DATA:(.+)$/g;

let extractedData = regex.exec(data);
// extractedData[1] == 'alpha'
// extractedData[2] == '678.90'

If implementing this in your scenario, substitute response.data for data.

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

When using the each() function, the array shows a length of zero and does not

Although I am well-versed in PHP, my understanding of JQuery is lacking and I'm experiencing some difficulty with arrays. Despite researching numerous forum posts on the topic, I still can't seem to get it right. I believe I have an array struct ...

Using JavaScript to detect the Facebook like button on a webpage

I am currently developing an application for Facebook using HTML and Javascript. My goal is to be able to detect when a user clicks the "Like" button on my company's Facebook page without needing to embed a separate "Like" button within my app itself. ...

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

Exploring the world of AJAX form with WordPress and making the most out of session variables

At my website, users have the ability to store session variables in two different locations. The first is through a PHP form on the single applicant page, and the second is through an AJAX form on the all applicants page. I utilize WP Session manager to ma ...

Utilize the fitBounds feature from GoogleMaps in Vuejs for seamless integration

I've been working on getting the map boundaries to work properly, using a method in conjunction with my existing initMap and askGeolocation methods. Despite my best efforts, I can't seem to get the bounds functionality working so that the map zo ...

Can you share the outcomes of executing a Node.js program in real-time?

Is there a method to execute a program (such as tcpdump) and have nodejs capture the console output in real-time to display in an HTML format without saving it? I am interested in running a program that displays information in the console, with the capabi ...

morris.js - displaying a dynamic line chart using JSON data

These are the resources I have: clicks.json index.html The contents of my clicks.json file: [ {"day":1,"clicks":"387"}, {"day":2,"clicks":"432"}, {"day":3,"clicks":"316"}, {"day":4,"clicks":"238"}, {"day":5,"clicks":"354"}, {"da ...

There is no 'Access-Control-Allow-Origin' header present on the requested resource in WordPress

I'm transferring posts from one WordPress site to another on the same server. To do this, I'm utilizing jQuery.ajax with the Rest API. However, I'm encountering an error message in the console. When trying to access '' from &apo ...

My website keeps crashing because the "wheel" event is being constantly triggered

import React, { useEffect, useState } from "react"; import "./Skill.css"; import { Fade } from "react-reveal"; function Skill({ name, color }) { const [style, setStyle] = useState({ borderBottom: `4px solid ${color}` }); ...

Is there a way to set the background image to scroll vertically in a looping pattern?

Is it possible to achieve this using only HTML5 and CSS3, or is JavaScript/jQuery necessary? ...

What could be causing the appearance of white lines in my rendered 3D obj file when using three.js?

I'm perplexed by the appearance of white lines in my rendered 3D model using three.js. Could these be part of the wireframe? It seems that some meshes weren't separated properly, leading to this issue. I'm unsure about how to remove the wire ...

What is the best way to detect if there are any active jQuery components on a website using WebDriver?

Currently, I am in the process of automating a web page that contains various JavaScript and jQuery functionalities using Selenium WebDriver. It has come to my attention that some posts mention the importance of waiting for the page to load completely befo ...

What could be causing the frontend to receive an empty object from the express server?

Struggling to understand how to execute this request and response interaction using JavaScript's fetch() along with an Express server. Here is the code for the server: var express = require('express'), stripeConnect = require('./r ...

Linking two socket.io clients together (Establishing a direct socket-to-socket connection that works across different browsers)

Can a direct P2P connection be established between two browsers using socket.io-client, bypassing the node.js server they are currently connected to? If possible, how? The goal is for clients A and B to communicate directly without going through the node. ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

Solution for displaying table cells in IE 7 and lower using Javascript

Lately, the community has come up with some amazing tools to push early versions of IE beyond their intended capabilities. For example, using multi-column CSS selectors. However, I've been struggling to find a JavaScript that can be loaded conditional ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

The Mean stack application is throwing an error message: "user.comparePassword is not

This section contains my user models in the file named "user.js". var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); let emailLengthChecker = (email) => { if (!email) { return false; } else { if (emai ...

Getting bounding box data from a 3D entity in A-Frame: A simple guide

Currently I'm immersed in a new aframe venture that requires me to import 3D objects of various sizes into my scene. I'm thinking ahead and would like to adjust the object to a specific size (such as a fixed height) before integrating it into the ...

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...