2015-12-22 34 views
0

我有以下的javascript ...Regex.test是給我一個錯誤

$.post(url, data, function (json) { 
     var patt = new RegExp('/^\[{"dID":/'); 
     if (patt.test(json)) { 

      //output json results formatted 
} else { 

     //error so output json string 
      $('#diaryTable').replaceWith(json);  

     } 
    }, 'json'); 

基本上我的JSON要麼是一個有效的JSON與開始

[{ 「難道」:

或將是

[{的ex.Message從嘗試卡子E xception ...}]

Unfotunately我得到的錯誤JavaScript運行錯誤:預期 ']' 在正則表達式

我檢查我的正則表達式/^[{ 「爲什麼」:/時帶有一些測試數據的RegEx101.com和我的測試按預期工作。任何想法的人?

+0

'VAR PATT =/^ \ [\ { 「爲什麼」:/;' –

+0

你需要躲避'['支架,如否則它充當一個Regex操作符。如果你想測試正則表達式,我覺得'regexr'是最好的網站。 – somethinghere

回答

0

好感謝所有誰試圖幫助......我想我這個問題的解釋是不是太清楚......

我已經通過檢查,如果我有一個有效的對象固定我的問題...一個有效的對象有一個沒價值,所以我已經使用...

if (typeof json[0].dID != 'undefined') { 
      // valid object 
      var out = ""; 
      var i; 
      var a = "N" 

      for (i = 0; i < json.length; i++) { 

       out += '<div class="dOuter' + a + '">'; 
       out += '<div class="dInner">' + json[i].dDate + '</div>'; 
       out += '<div class="dInner">' + json[i].dRef + '</div>'; 
       out += '<div class="dInner">' + json[i].dTeam + '</div>'; 
       out += '<div class="dInner">' + json[i].dCreatedBy + '</div>'; 
       out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>'; 
       out += '<div class="dServer">' + json[i].dServer + '</div>'; 
       out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>'; 

       if (a == "N") { 
        a = "A"; 
       } else { 
        a = "N"; 
       } 
      } 

      $('#diaryTable').replaceWith(out); 
     } 

     else { 
      //error so output json string 
      $('#diaryTable').replaceWith(json);  
     }