Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a pipe delimited key-value pair separated by '=' symbol

We are receiving an input parameter value as a pipe-delimited key-value pair, separated with = symbols. For example:

"|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|"

So the format is: |KEY=VALUE|KEY_2=VALUE_2|....|KEY_n=VALUE_n|

I need to split it into a JSON object. So, my object should be :

{
 'User':'0101',
 'Name':'ImNewUser',
 'IsAdmin':'0',
 'RefId'='23ae2123cd223bf235'
}

What will be best way to go, since there are multiple options:

  • I can use split with | and again on each element split with =.
  • I can depend on regular expression and do string replace.
  • Split it with = remove trailing | symbol and associate two different arrays with indexes.

Can anyone tell me the best/most efficient way of doing this in JavaScript (programming in Node.js)?

like image 907
Amol M Kulkarni Avatar asked Apr 27 '13 07:04

Amol M Kulkarni


2 Answers

The first one sounds good:

var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";


var result = {};
str.split('|').forEach(function(x){
    var arr = x.split('=');
    arr[1] && (result[arr[0]] = arr[1]);
});
like image 133
Paul Avatar answered Sep 20 '22 16:09

Paul


If you do decide to use regex, make sure it's block rockin' regex like this:

var result = {};

s.replace(/([^=|]+)=([^|]*)/g, function(noStep3, a, b) { result[a] = b; });

regex railroad

like image 25
Billy Moon Avatar answered Sep 18 '22 16:09

Billy Moon