Obtener texto entre comillas [JavaScript]

  • Hacker007
  • Proficient
  • Proficient
  • Avatar de Usuario
  • Registrado: Abr 07, 2004
  • Mensajes: 371
  • Loc: Riverside, CA
  • Status: Offline

Nota Octubre 14th, 2012, 2:20 pm

Bueno, ha sido mucho tiempo desde que he posteado aquí, pero realmente necesito ayuda! Estoy trabajando en una HTA y utiliza JavaScript para código mucho de ella. Una de las tareas dentro de la aplicación es leer un fichero y tomar pares clave/valor y cargarlos en una matriz asociativa. He logrado esto, pero quiero encontrar una forma más efectiva de hacer esto para acelerar el proceso y mantener el código más limpio (menos desordenado). Aquí está mi código:

ActiveEventsLog.dbf (este es el archivo que se lee)
Código: [ Select ]
--------- ACTIVE EVENTS ----------

[MACH-01] = "0000001"
[MACH-02] = "0000002"
[MACH-03] = "0000003"
  1. --------- ACTIVE EVENTS ----------
  2. [MACH-01] = "0000001"
  3. [MACH-02] = "0000002"
  4. [MACH-03] = "0000003"


Aquí es parte del.Archivo HTA (la función de JavaScript que convierte el contenido del archivo ActiveEventsLog.dbf (arriba) en una matriz asociativa (o más bien un objeto funciona como una matriz asociativa--maldito JS) tiró en comentarios detallados para su convience
Código: [ Select ]
function getActiveEvents() {

    //Just trust me, the line below loads "ActiveEventsLog.dbf" as a String
    var ActiveEventsLog = queryActiveEvents();
    
    //This object is what I return at the end..
    var ActiveEvents = new Object();
    
    //Turn the string into an array.. each new line is one array element
    ActiveEventsLog = ActiveEventsLog.split("\r\n");
    
    //Loop through each array element (each line of original file)
    for ( d = 0; d < ActiveEventsLog.length; d++ )
    {

        //If it's a Key/Value Pair line
        if ( ActiveEventsLog[d].charAt(0) == "[" )
        {
            //Next 5 Lines Rips out the [] in the "Key"
            l = "";
            l = ActiveEventsLog[d];
            l = l.split("]");
            l = l[0];
            l = l.replace("[", "");

            //Next 8 Lines Rips out the QUOTES and SPACES in the "Value"
            k = "";
            k = ActiveEventsLog[d];
            k = k.split("=");
            k = k[1];
            k = k.replace("\"", "");
            k = k.replace("\"", "");
            k = k.replace(" ", "");
            k = k.replace(" ", "");
            
            //If BOTH Key AND Value are present, add it to the return variable
            if ( ( l != "" ) & ( k != "") )
            {
                ActiveEvents[''+l+''] = k;
            }
        }
    }
    
    //Return our Associative Array(Object)
    return ActiveEvents;
}
  1. function getActiveEvents() {
  2.     //Just trust me, the line below loads "ActiveEventsLog.dbf" as a String
  3.     var ActiveEventsLog = queryActiveEvents();
  4.     
  5.     //This object is what I return at the end..
  6.     var ActiveEvents = new Object();
  7.     
  8.     //Turn the string into an array.. each new line is one array element
  9.     ActiveEventsLog = ActiveEventsLog.split("\r\n");
  10.     
  11.     //Loop through each array element (each line of original file)
  12.     for ( d = 0; d < ActiveEventsLog.length; d++ )
  13.     {
  14.         //If it's a Key/Value Pair line
  15.         if ( ActiveEventsLog[d].charAt(0) == "[" )
  16.         {
  17.             //Next 5 Lines Rips out the [] in the "Key"
  18.             l = "";
  19.             l = ActiveEventsLog[d];
  20.             l = l.split("]");
  21.             l = l[0];
  22.             l = l.replace("[", "");
  23.             //Next 8 Lines Rips out the QUOTES and SPACES in the "Value"
  24.             k = "";
  25.             k = ActiveEventsLog[d];
  26.             k = k.split("=");
  27.             k = k[1];
  28.             k = k.replace("\"", "");
  29.             k = k.replace("\"", "");
  30.             k = k.replace(" ", "");
  31.             k = k.replace(" ", "");
  32.             
  33.             //If BOTH Key AND Value are present, add it to the return variable
  34.             if ( ( l != "" ) & ( k != "") )
  35.             {
  36.                 ActiveEvents[''+l+''] = k;
  37.             }
  38.         }
  39.     }
  40.     
  41.     //Return our Associative Array(Object)
  42.     return ActiveEvents;
  43. }





Así como usted puede ver, utilizar 8 líneas de código para sacar el Id de evento desde el archivo (el número de 7 dígitos en citas de ActiveEventsLog.dbf) funciona, pero creo que funcionaría mejor regex o algo, o tal vez un replace_all tipo de función (tengo que reemplazar cada cotización con valor nulo individualmente ahora). Ojalá alguien aquí (hace joebert todavía post aquí??) me puede dar una idea, como quiero mi código como ligero y eficiente como sea posible.

¡ Muchas gracias!
"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." -Martin Golding
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Octubre 14th, 2012, 2:20 pm

  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Diciembre 6th, 2012, 11:14 am

Podría convertir la cadena de información en JSON y luego utilice un json decodificar la función convertir en una matriz (objeto)

Rápidamente hice esto para convertir el texto de ejemplo en json
JAVASCRIPT Código: [ Select ]
function text_to_json(text) {
   
   // Turn [ and ] into "
   text = text.split('[').join('"');
   text = text.split(']').join('"');
   
   // Turn = into :
   text = text.split('=').join(':');
   
   // Break on hard space
   text = text.split("\r\n");
   
   // Join on a comma
   text = text.join(',');
   
   // Wrap in { }
   text = '{' + text + '}';
   
   // Return text
   return text;
   
}
 
// Your test info
var text = '[MACH-01] = "0000001"' + "\r\n" + '[MACH-02] = "0000002"' + "\r\n" + '[MACH-03] = "0000003"';
 
// Object like assoc array
var array_object = JSON.parse(text_to_json(text));
 
 
  1. function text_to_json(text) {
  2.    
  3.    // Turn [ and ] into "
  4.    text = text.split('[').join('"');
  5.    text = text.split(']').join('"');
  6.    
  7.    // Turn = into :
  8.    text = text.split('=').join(':');
  9.    
  10.    // Break on hard space
  11.    text = text.split("\r\n");
  12.    
  13.    // Join on a comma
  14.    text = text.join(',');
  15.    
  16.    // Wrap in { }
  17.    text = '{' + text + '}';
  18.    
  19.    // Return text
  20.    return text;
  21.    
  22. }
  23.  
  24. // Your test info
  25. var text = '[MACH-01] = "0000001"' + "\r\n" + '[MACH-02] = "0000002"' + "\r\n" + '[MACH-03] = "0000003"';
  26.  
  27. // Object like assoc array
  28. var array_object = JSON.parse(text_to_json(text));
  29.  
  30.  


La mayoría de los navegadores soportan JSON.parse(); para otros puede utilizar este script.https://github.com/douglascrockford/JSO ... r/json2.js

Publicar Información

  • Total de mensajes en este tema: 2 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 131 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC