Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to parse a text like XML to a javascript object
    text
    copied!<p>I created a function to do this.</p> <pre><code>var text="adsf [name]Victor[/name] dummytext [name]Elliot[/name] asdf [name]Jake[/name] asdf [foo]bar[/foo]"; alert( readTags(text,'name') ); //Victor,Elliot,Jake alert( readTags(text,'foo') ); //bar </code></pre> <p>but now I like to implement a function that receive a string like this</p> <pre><code>[person] [name]jake[/name] [age]12[/age] [/person] </code></pre> <p>and return a object like this</p> <pre><code>var object={}; object['person']={}; object['name']='jake'; object['age']='12'; return(object); </code></pre> <p>but I don't know how to loop through the text. How to deal with starting and ending tags? like</p> <pre><code>[tag] [tag]value[/tag] [/tag] </code></pre> <p>I thought to find starting tag from left and ending tag from the right using <code>indexOf('[tag]')</code> and <code>lastindexOf('[/tag]')</code></p> <p>but doesn't work in this situation</p> <pre><code>[tag]value[/tag] [tag]value[/tag] </code></pre> <p>this is the previous function</p> <pre><code>function readTags(str,property){ var beginTag='['+property+']'; var endTag='[/'+property+']'; var values=new Array(0); while(str.indexOf(beginTag)!=-1){ values[values.length]=strBetween(str,beginTag,endTag); str=str.substring(str.indexOf(endTag)+endTag.length); } return(values); } function strBetween(string,strBegin,strEnd){ //StrBetween("abcdef","b","e") //return "cd" var posBegin, posEnd; posBegin=string.indexOf(strBegin); string=string.substring(posBegin + strBegin.length); posEnd=string.indexOf(strEnd); string=string.substring(0,posEnd); if ((posBegin==-1)||(posEnd==-1)){ return(null); }else{ return(string); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload