Search code examples
javascriptjsonreplacesplitstring-parsing

How to split a string with comma separated pairs of colon separated keys and values and pass it into a javascript object?


Currently using str.split(',') on a string and passing it into an array (also simultaneously removing next lines and " from the string). The string looks like this:


let array = [];
const string = "a_key : a_value, b_key: b_value, c_key: c_value";


array = string.replace(/(\r\n|\n|\r|\\n)/gm, ' ').replace(/"/g, '').split(',');

The results in:

console.log(array);

//result:
['a_key : a_value' 'b_key : b_value' 'c_key : c_value']

Those values need to be accessed by their key and processed further, it would be better as an object.

Any one see what I'm missing in the regular expression chain?

Summary:

Turn this:

"a_key : a_value, b_key: b_value, c_key: c_value"

into this:


{'a_key' : 'a_value', 'b_key' : 'b_value', 'c_key' : 'c_value'}


Solution

  • An alternative solution improves the use of regex you made. This could be done by capturing the groups delimited by : and , maintaining the order of an object. Look:

    const string = "a_key : a_value, b_key: b_value, c_key: c_value";
    const obj = {}, re = new RegExp('(.*?):(.*?)(?:,|$)','g')
    
    string.replace(re, (_, key, value) => obj[key.trim()] = value.trim())
    
    console.log(obj)

    How this regex works?

      (.*?):  matches anything lazily until colon
      (.*?)(?:,|$)  matches anything lazily until comma or end of string
    

    Here if you want to visualize regex in action.