2012-12-14 34 views
1

我有這種類型的JSON數組:支架正則表達式的Javascript

[ 
    { text: '[Chapter1](chapter1.html)'}, 
    { text: '[Chapter2](chapter2.html)'}, 
    { text: '[Chapter3](chapter3.html)'}, 
    { text: '[Chapter4](chapter4.html)'} 
] 

在試圖環槽的陣列和取括號中的文本(第1章,第2章等)I found a RegExp here at StackOverflow

var aResponse = JSON.parse(body).desc; // the array described above 
var result = []; 
var sectionRegex = /\[(.*?)\]/; 
for(var x in aResponse) { 
    result.push(sectionRegex.exec(aResponse[x].text)); 
    //console.log(aResponse[x].text) correctly returns the text value 
} 
console.log(result); 

應打印:

["Chapter1","Chapter2","Chapter3","Chapter4"] 

但是我得到了多個陣列怪異的長期結果:

[ '[Chapter1]', 
    'Chapter1', 
    index: 0, 
    input: '[Chapter1](chapter1.html)' ] 
[ '[Chapter2]', 
    'Chapter2', 
    index: 0, 
    input: '[Chapter2](chapter2.html)' ] 
[ '[Chapter3]', 
    'Chapter3', 
    index: 0, 
    input: '[Chapter3](chapter3.html)' ] 
[ '[Chapter4]', 
    'Chapter4', 
    index: 0, 
    input: '[Chapter4](chapter4.html)' ] 

我缺少什麼?我吮吸正則表達式。

+0

不知道你用JSON.parse那裏所做的事情,但這裏有一個[** ** FIDDLE(HTTP://的jsfiddle。淨/ xGXD8/2 /),也許這使得它更清晰? – adeneo

+0

我使用GET請求從外部服務器獲取JSON。我不知道什麼是錯的。我檢查了一切。它仍然返回甚至不在json數組中的字段。 – jviotti

+0

@adeneo我附上了我得到的結果 – jviotti

回答

1

The exec method of regular expressions不僅返回匹配的文本,還返回許多其他信息,包括輸入,匹配索引,匹配文本和所有捕獲組的文本。你可能想比賽第1組:

result.push(sectionRegex.exec(aResponse[x].text)[1]); 

除此之外,你不應該使用for(...in...)循環遍歷數組,因爲這將打破,如果任何方法添加到Arrayprototype。 (例如,forEach墊片)

0

沒有你想象的那麼奇怪,每個regex.exec結果實際上是一個看起來像其中一個塊的對象,它包含整個文本匹配,子組匹配(你只有一個子組,並且它是你真正想要的結果),匹配成功的輸入內的索引和給出的輸入。

所有這些都是成功比賽的有效結果。

簡短的回答是,你想只推動第二個數組元素到結果中。
Like regex.exec(text)[1]

+1

更多信息:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec –

0

您使用的正則表達式將返回一個數組。 第一個元素將是要測試的字符串。下一個元素將是括號 之間的matche試試這個:

result.push(sectionRegex.exec(aResponse[x].text)[1]);