0

Html

I have followig html:

<span>
Array
(
    [namePerson/first] => firstnamedata
    [namePerson/last] => lastnamedata
    [namePerson] => firstnamedata lastnamedata
    [person/gender] => genderdata
)
</span>

Goal

Can I somehow achieve something like this?

var myArray = $("span").text();
alert(myArray["namePerson/first"]);

I mean to litterally interpret the string as an array and access it's keys/values.

skrln
  • 542
  • 2
  • 8
  • 19
  • Read the JavaScript array reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – AurA Sep 17 '13 at 09:39
  • 1
    @AurA I'm pretty sure he knows what an array is. He's asking how to make one from the html above. – Reinstate Monica Cellio Sep 17 '13 at 09:40
  • 1
    Are you by chance trying to get a php-array into your javascript? if you do please use the json format. – cptnk Sep 17 '13 at 09:40
  • First of all that associative array is called an object in JavaScript, and no there is no nice way to eval that construct to a JavaScript construct the way you want it. – Octavian Helm Sep 17 '13 at 09:42
  • Then he must basically get value from the span tag... parse it using string delimiters and then populate the array.. – AurA Sep 17 '13 at 09:43
  • possible duplicate of [Convert php array to Javascript](http://stackoverflow.com/questions/5618925/convert-php-array-to-javascript) – Ram Sep 17 '13 at 09:43
  • I don't have access to the php object, this html output is the only thing I have to work with. It is printed to a page (outside of my control) in this format, and I can only access the printed HTML. – skrln Sep 17 '13 at 09:48
  • Yea, then you'll have to write a parser. – Octavian Helm Sep 17 '13 at 09:57
  • Ok, thanks I'll give the parser a go. – skrln Sep 17 '13 at 09:59

1 Answers1

1

You could write a basic parser.

function nextC(i, text) {
  if (i < text.length)
    return text.charAt(i);
  return "";
}

function skipSpace(i, text) {
  while (c == " ")
    c = nextC(++i, text);
  return i;
}  

function parseObj(text) {
  var lablel = "";
  var value = "";
  var obj = {};
  for (var i = 0; i < text.length; i++) {
    var c = text.charAt(i);
    if (c == "[") {
      while (c != "]") {
        c = nextC(++i, text);
        label += c;
      }
    } else if (c == " ") {
      i = skipSpace(i, text);
      c = nextC(i, text);
      if (c == "=") {
        c = nextC(++i, text);
        if (c == ">" {
          i = skipSpace(i, text);
          c = nextC(i, text);
          while (c != "\n") {
            c = nextC(++i, text);
            value += c;  
          }          
          obj[label] = value;
        }
      }
    }
  }
  return obj;
}
var text = $("span").text();
var obj = parseObj(text);
alert(obj["namePerson/first"]);

Note This may be prone to bugs. If you are trying to transfer data from server to client, try using JSON or XML.

azz
  • 5,852
  • 3
  • 30
  • 58