I'd like to extract values from below key:value pairs being sent in as a single string:
"var1:value1,var2:value2,var3:value3"
I have to use JavaScript and unfortunately I am unable to use an array and loop through the var1,var2,var3 keys due to the regex unable to handle variables... I am wondering if there is a way to do this in JS?
See below:
function onBefore(current, previous)
{
if (current.key != '' || current.key != null)
{
if (current.key.match(/var1/)) {
var assign = current.key.match(/(?:var1:)([^,]+)/)[1];
} else if (current.key.match(/var2/)) {
var assign = current.key.match(/(?:var2:)([^,]+)/)[1];
} else if (current.key.match(/var3/)) {
var assign = current.key.match(/(?:var3:)([^,]+)/)[1];
} else if (current.key.match(/var4/)) {
var assign = current.key.match(/(?:var4:)([^,]+)/)[1];
}
} else {
assign = "None";
}
if (assign != "None") {
current.node = assign;
}
}
}
@revo thanks for that answer, for others to benefit... here's the final code:
var str = "keyIcareabout:test3end,something:value,nothing:burger";
var node = "None";
function valueOf(key) {
return (m = (new RegExp("\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null;
}
if (str != '' || str !== null)
{
var resources = ["keyIcareabout","somethingelseIcareabout"];
for (i = 0; i < resources.length; i++)
{
if (str.match(resources[i]))
{
node = valueOf(resources[i]);
}
}
}
if (node != "None")
{
console.log("Matched " + node + " with node field ");
}