Charlie
Charlie

Reputation: 11777

Split to get the text between separators?

I am making a cross domain AJAX request, and because of this, I can't pass the original array from the PHP page to my HTML page. Instead, the request gets the results as a string. I have it set up so that the syntax looks like this:

([SCHOOL] Name [/SCHOOL][STATUS] Status [/STATUS])
([SCHOOL] Other name [/SCHOOL][STATUS] Other status [/STATUS])

On my HTML page, I want to be able to form an array from these different values, in the form of:

Array (
    [0] =>
        [0] Name
        [1] Other
    [1] =>
        [0] Name 
        [1] Other status
)

This way, I can use a for loop to get specific values.

The only problem with is that split only does just that, splits things. Is there a way in JS to find the text within separators, and form an array from it? In the example again, it'd find all text within the parenthesis, and form the first array, then within that array, use the text between [SCHOOL][/SCHOOL] for the first object, and use the text between [STATUS][/STATUS] for the second object.

Upvotes: 0

Views: 211

Answers (1)

Billy Moon
Billy Moon

Reputation: 58531

Ideally, you would use something more suited to storing arrays on the server side. I would recommend JSON. This would be trivial to encode using php, and decode using javascript.

If you do not have that option server side, then you can use regex to parse your text. However, you must be sure that the contents does not have your delimiters within in it.

It is not clear how you get your target data structure from your source, but I would expect something like this might work for you:

str = "([SCHOOL] Name [/SCHOOL][STATUS] Status [/STATUS])\n\
([SCHOOL] Other name [/SCHOOL][STATUS] Other status [/STATUS])"

arr  =[]
m = str.match(/\(.+?\)/g)
for(i in m){
    matches = m[i].match(/\(\[SCHOOL\](.+?)\[\/SCHOOL\]\[STATUS\](.+?)\[\/STATUS\]\)/)
    arr.push([matches[1],matches[2]])
}

console.dir(arr)

Upvotes: 1

Related Questions