Javascript / DOM, analizando la cadena de clave / valor

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.

Aquí está el código que he escrito:

    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 pantallas "KEY:a1 VAL:123.45" en lugar de lo esperado "123.45" (y por supuesto el 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 y 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!

preguntado el 09 de marzo de 12 a las 17:03

KEY: is not a tag name and reply not an object -

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. -

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) -

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) -

1 Respuestas

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'

En tu caso, usarías request.responseText en lugar de value.

respondido 09 mar '12, 18:03

Don't forget to accept the answer that helped you the most ;) - Félix Kling

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.