2012-06-27 20 views
1

我有這樣的標記,如何獲取這些屬性的每個鍵和值並將其填充到數組中(數量屬性將增加)的最佳方式?如何在Javascript上解析括號標記

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

,並得到結果數組:

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

它是什麼格式?這不是一個數組 – Blaster

+3

這是字符串嗎? – totten

+0

是的,它是一個字符串。 –

回答

2

這可能你想要做什麼,但它假定tag已經在你所描述的格式,即[data ... ]奇異發生。

此外,正則表達式純粹是基於我在你的問題中看到的;不確定它是否會破壞其他字符串。

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

最好的解決方案,我剛剛完成正則表達式:) – totten

0
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'}}] 

這適用於任意數量的字符串中的標籤。標籤的名稱無關緊要。

1

由於數據中有字符串鍵,因此請使用jquery對象而不是數組。

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); 

試試這個代碼。它可能會幫助你。

這裏是DEMO

雖然它也可以,如果你把你的代碼的一些細節進行更加優化。

+0

如果字符串在值中或者在']後面包含一個'=',你會得到一些奇怪的結果。 –