-2

How can I use regex in javascript to put items and its values in a array ?

This is my data sample:

battery.voltage: 13.50
battery.voltage.nominal: 12.0
beeper.status: enabled
device.type: ups
driver.name: blazer_ser
driver.parameter.pollinterval: 2

Thanks

user89300
  • 5
  • 2

3 Answers3

0

Why use regular expression, you can simply use substr and indexOf. Assuming you have your list stored in an array you can simply loop through the entries and split on the first occurrence of a colon.

var items = [...]; // Your items.
var arr = {};
for (var i = items.length - 1; i >= 0; i--) {
    var key = items[i].substr(0, items[i].indexOf(':'));
    var value = items[i].substr(items[i].indexOf(':') + 1).trim();
    arr[key] = value;
}

This solution will only work in browsers implementing the trim method. If you want to be on the save side you can overwrite the String.prototype and add the trim method. (See Trim string in JavaScript?)

If you have your items as a string separated by newlines you can easily split it into an array through split;

var list = "battery.voltage: 13.50\n"
         + "battery.voltage.nominal: 12.0\n"
         + "beeper.status: enabled\n"
         + "device.type: ups\n"
         + "driver.name: blazer_ser\n"
         + "driver.parameter.pollinterval: 2";​​
var items = list.split(/\n/);

DEMO

Community
  • 1
  • 1
clentfort
  • 2,454
  • 17
  • 19
0

use the below code to do that... here variable data contains your data...

data=data.split(/\n+/);
var output={};
for(var i=0;i<data.length;i++){
     var a=data[i].split(/:\040+/);
     output[a[0]]=a[1];
}

These codes will give you an array like below...

Array ( 
    battery.voltage: "13.50",
    battery.voltage: "12.0",
    beeper.status: "enabled",
    device.type: "ups",
    driver.name: "blazer_ser",
    driver.parameter.pollinterval: "2"
)

Example:

output['driver.name'] === "blazer_ser"
Naz
  • 2,520
  • 2
  • 16
  • 23
0

Here's a solution that makes only one pass through the string data using a single regex:

var list = "battery.voltage: 13.50\n"
         + "battery.voltage.nominal: 12.0\n"
         + "beeper.status: enabled\n"
         + "device.type: ups\n"
         + "driver.name: blazer_ser\n"
         + "driver.parameter.pollinterval: 2";


function parse(data) {
    var match, result = {};            
    var pattern = /\s*([^:\s]+)\s*:\s*([^:\s]+)$/gm; 
    while (match = pattern.exec(data)) {
        result[match[1]] = match[2];
    }
    return result;
}

var test = parse(list);

// dump array
for (var i in test) 
    console.log(i + ": " + test[i]);

// select one
console.log(test["driver.parameter.pollinterval"]);

Click here to try it out on jsfiddle

John R
  • 126
  • 1
  • 3