0

I send a string from a server to the Firefox Browser in the format below:

"KEY:a1 VAL:123.45"

And this string can contain many such records.

Here is the code I have written:

    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";
    }

val displays "KEY:a1 VAL:123.45" instead of the expected "123.45" (and of course the key variable is also wrong, not matching a table cell, just picking the first one in the table).

I don't even know how to display the key and val values (document.write() and alert() do nothing and I don't see how to trace this code in Firefox).

Any idea, tip, correction, or code example is welcome but please don't recommend using any library, I want to do it with little code.

EDIT: from the two comments, I understand that there are two distinct ways to proceed: either using DOM objects and HTML tags, or using 'strings'. I would prefer to keep using the format above, so please guide me to a 'string' solution. Thanks!

4
  • KEY: is not a tag name and reply not an object Commented Mar 9, 2012 at 17:12
  • reply is not a DOM element, it's a string. Strings don't have a a method getElementsByTagName and that string does not even contain HTML. Commented Mar 9, 2012 at 17:47
  • Thanks for the information. Can you elaborate how should I do it then? (either creating 'objects' and using HTML tags, or parsing a 'string' - the latter having my favor) Commented Mar 9, 2012 at 17:53
  • Thanks for the information. Can you elaborate how should I do it then? (either creating 'objects' and using HTML tags, or parsing a 'string' - the latter having my favor) Commented Mar 9, 2012 at 17:53

1 Answer 1

2

You can use a simple regular expression to extract the information from the string:

var value = "KEY:a1 VAL:123.45"​,
    pattern = /KEY:(\S+) VAL:(.+)$/g;

var result = pattern.exec(value);
// result[1] == 'a1'
// result[2] == '123.45'

In your case, you'd use request.responseText instead of value.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to accept the answer that helped you the most ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.