2017-09-22 42 views
0

我最初有形式如何用JS中的幾個鍵和值分隔輸入sting?

「平均事件大小的輸入字符串:0.000 KB - 軌道計數器:1986836 - N. L1A等待(OFIFO):0 - 配置FED ID:654(0x28e) - JTAG訪問模式:VME ================================================ ======================= SPY中的詞fifo:219716 OFIFO中的事件:2000 Last finally triggered:0x1 L1A counter:4027452「

I使用以下代碼從中獲得了鍵和值:

infoStringArray = infoString.split("\n"); 
    for (var i = 0, size = infoStringArray.length; i < size ; i++){ 
     if (infoStringArray[i].search(":") != -1){ 
      var keyvalue = infoStringArray[i].split(":"); 
      var key = keyvalue[0].trim(); 
      if (key[0] == "-"){ 
       key = key.substring(2); 
      } 
      board_data.boarddata[key] = keyvalue[1].trim(); 
     } 
    } 

這很容易,因爲不同鍵和值由' - '分隔。然而,現在我得到了一串表格:

「SRP通道時鐘:OK DCC/TCC通道時鐘:OK TTC 40MHz時鐘:OK RC狀態:空閒SRP狀態:WaiForL1AEnable卡配置:是不同步:否「

唯一的分隔符是空格,但它也用於某些鍵的名稱。我正在尋找關於如何做到這一點的想法。

+0

如果分離是一個換行符(\ n) ,這很容易,但作爲一個空白...我覺得很難實現。 –

+0

你不能沒有給我們更多的規則。例如。我們如何知道第一個值是「219716事件」還是「219716」,計算機使用邏輯,而我們在這裏沒有。 – Keith

回答

0

該解決方案適用於這樣的假設值將始終是一個字:

var input = "SRP channel clock: OK DCC/TCC channel clock: OK TTC 40MHz clock: OK RC state: Idle SRP state: WaiForL1AEnable Card configured: yes Out of sync: no "; 
 

 
// Initial split operation 
 
var ary = input.split(":"); 
 

 
for(var i = 0; i < ary.length-1; i++){ 
 
    // Remove leading or trailing spaces 
 
    ary[i] = ary[i].trim(); 
 
    
 
    // If we are on a value 
 
    if(i % 2 !== 0){ 
 
    // Split the value portion (string) into a temporary array 
 
    var tempAry = ary[i].split(/\s/); 
 
    
 
    // Set the value to only the first index of the temporary array and then 
 
    // drop that value from the temporary array so it doesn't wind up being 
 
    // part of the remaining string because that is now the next key. 
 
    ary[i] = tempAry.shift(); 
 
    
 
    // Reassemble the remaining words 
 
    var x = tempAry.join(" "); 
 
    
 
    // Insert the next proper key into the array at the next index 
 
    ary.splice([i+1],0,x); 
 
    } 
 

 
} 
 

 
// Now that the keys and values have been separated correctly, 
 
// reassemble them into a final object 
 
var result = {} 
 
for(var x = 0; x < ary.length; x++){ 
 
    // If we are on a key, write a new object property and its corresponding value 
 
    (x % 2 === 0) ? result[ary[x]] = ary[x+1] : ""; 
 
} 
 

 
// Show the final object: 
 
console.log(result);

+0

爲解釋工作答案的投票?! –

+0

你的解決方案已經結束了複雜 –

+0

@MarcinMalinowski它肯定比你的答案更多的代碼,但它的工作原理和很好的解釋。不是投票的理由。 –

0

var infoString = "SRP channel clock: OK DCC/TCC channel clock: OK TTC 40MHz clock: OK RC state: Idle SRP state: WaiForL1AEnable Card configured: yes Out of sync: no"; 
 

 
infoString.replace(/(.*?):\s(\w+)[\s-]*/g, function (match, key, value) { 
 
    console.log(key, '-', value); 
 
});

相關問題