Here is one way to do it:
var str = "desc: random text string, sender: James, se-status: red, action: runs, target: John, ta-status: blue, status-apply: red, lore: lore ipsum dolor sit amet";
var obj = {};
str.split(',').forEach(function(line) {
var l = line.split(':');
obj[l[0].trim()] = (l[1].trim());
});
console.log(obj);
console.log(JSON.stringify(obj));
as a function:
function myStrToObj(str) {
var obj = {};
str.split(',').forEach(function(line) {
var l = line.split(':');
obj[l[0].trim()] = (l[1].trim());
});
return obj;
}
Edit after explanation from OP
a better parser:
function myStrToObj(str) {
var lastColon = lastComma = -1;
var key = value = '';
var obj = {};
for(var i = 0; i < str.length; i++) {
if (str[i] == ':') {
if (lastColon > 0) {
value = str.substring(lastColon + 1, lastComma).trim();
obj[key] = value;
key = str.substring(lastComma + 1, i).trim();
} else
key = str.substring(0, i).trim();
lastColon = i;
};
if (str[i] == ',')
lastComma = i;
};
value = str.substring(lastColon + 1, str.length).trim();
obj[key] = value;
return obj;
}
var str = "desc: random text string, sender: James, se-status: red, problem-field: I'm a problem field, I'm a problem field, action: runs, target: John, ta-status: blue, status-apply: red, lore: lore ipsum dolor sit amet";
var obj = myStrToObj(str);
console.log(obj);
I put a JSFiddle with it here: https://jsfiddle.net/gnLk6fdd/14/
Edit based on Redu's answer
As I saw Redu's answer I thought it would be much better to create a regex to this. But the problem with his answer is that the field names have to be fixed. I tried to create a regex with capturing groups instead of my answer . My idea was to capture the group, repeat and then go back to last comma or beggining. But my knowlege of regex doesn't get that far.
So I created a question to see if someone can create a regex to this:
How can I create a regex to parse this string
Based on the question I linked above and the corresponding answer by Thomas Ayoub, I saw that if you get Redu's answer and just replace regex by:
var r = /([\w-]+):([\w,\s']+)(?:,|$)/g;
You can check string without fixed fields.And it's a much better solution than my for loop.
Demo: https://jsfiddle.net/yao97m4s/7/
,, or is it a safe delimiter?