如何在JS中将输入sting与几个键和值分开?

时间:2017-09-22 19:24:39

标签: javascript

我最初有一个

形式的输入字符串

“平均事件大小:0.000 KB - 轨道计数器:1986836 - N. L1A等待(OFIFO):0 - 配置FED ID:654(0x28e) - JTAG访问模式:VME ========== ================================================== =========== SPY fifo中的单词:219716 OFIFO中的事件:2000最后一串触发:0x1 L1A计数器:4027452“

我使用以下代码从中获取了键和值:

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卡配置:是不同步:否”

唯一的分隔符是空格,但它也用在某些键的名称中。我正在寻找有关如何做到这一点的想法。

2 个答案:

答案 0 :(得分:0)

此解决方案的前提是该值始终为单个词:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分: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);
});