0
votes

I am getting a user input in the form of

key1=value1,key2=value2,key3=value3

and there can be any number of key value pairs,

I have written following regular expression to evaluate above string.

[a-z0-9]+(:|=)[a-z0-9]+

but I am not so sure , how to check the multiple of key value pairs, this string I have written can evaluate one key value pair, I want it make it evaluate hole string of key value pairs. highly appreciate any advice on this

3

3 Answers

1
votes

A common approach is to (ab)use replace to do the job in one shot:

str = "key1=value1,key2=value2,key3=value3"

re = /(\w+)[:=](\w+)/g

obj = {}

str.replace(re, (_, $1, $2) => obj[$1] = $2)

console.log(obj)
1
votes

Try

([a-z0-9]+(:|=)[a-z0-9]+,?)+

To remove a trailing comma

if(str.substr(-1) === ',')
  str = str.substr(0, str.length - 1)
1
votes

Try this regex (\w+)[:=](\w+),?, in which group 1 matches the key and group 2 matches the values.

You can also use split, it might be faster.

var input = "your input";
var pairs = input.split(",")
for (i = 0; i < pairs.length; i++) {
    var parts = pairs[i].split(/[:=]/);
    var key = parts[0];
    var value = parts[1]
}