Jeg Bagus
Jeg Bagus

Reputation: 5075

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?

myData = '[data attr1="value1" attr2="value2" attr3="value3"]';

and get result array :

var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...

Upvotes: 1

Views: 901

Answers (3)

Nishu Tayal
Nishu Tayal

Reputation: 20840

Since you have string key in the data, use jquery object instead of array.

var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
    var x = str_arr[val].split('=');
    arr[x[0]]  = x[1].replace('"','').slice(0,-1);

});
console.log(arr);

Try this code. It may help you.

Here is the DEMO

Though it can be more optimized if you put some more details about your code.

Upvotes: 1

Markus Jarderot
Markus Jarderot

Reputation: 89171

var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;

function parse(text) {
    var result = [];
    tagRe.lastIndex = 0; // reset start position

    var tagMatch = tagRe.exec(text);
    while (tagMatch) {
        var currentTag = { 'name': tagMatch[1], 'attrs': {} };

        var attrString = tagMatch[2];
        attrRe.lastIndex = 0;

        var attrMatch = attrRe.exec(attrString);
        while (attrMatch) {
            var attrName = attrMatch[1];
            var attrValue = attrMatch[2];

            currentTag.attrs[attrName] = attrValue;

            attrMatch = attrRe.exec(attrString); // next match
        }
        result.push(currentTag);

        tagMatch = tagRe.exec(text);
    }
    return result;
}

parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]

This works for any number of tags in the string. The name of the tag does not matter.

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173572

This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].

Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.

function decode(tag)
{
    var r = /(\w+)="([^"]*)"/g,
    h = {};
    while ((m = r.exec(tag)) !== null) {
        h[m[1]] = m[2];
    }
    return h;
}

Upvotes: 2

Related Questions