2

I have the following string

server:all, nit:4545, search:dql has map

with the regular expression /(\w+):((?:"[^"]*"|[^:,])*)/g I get

["server:all", "nit:4545", "search:dql has map"] //Array

But I want to get

{server:"all","nit":"4545","search":"dql has map"}

OR

[{server:"all"},{"nit":"4545"},{"search":"dql has map"}]

3 Answers 3

4

You can use a simple regex for key:value and use a look using exec:

var str = 'server:all, nit:4545, search:dql has map';
var re = /([\w-]+):([^,]+)/g;

var m;
var map = {};

while ((m = re.exec(str)) != null) {
  map[m[1]] = m[2];
}

console.log(map);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use String#replace to loop over the matches and captures and assign those to an empty object.

const string = 'server:all, nit:4545, search:dql has map';
const regex = /(\w+):((?:"[^"]*"|[^:,])*)/g;
const map = {};

string.replace(regex, (m, c1, c2) => {
  map[c1] = c2;
});

console.log(map);

2 Comments

This does work, indeed, but using replace when you can just use the regex#exec without the need to modify the original string, seems unnecessary
@dquijada, the original string is not modified (did you try logging string after the replace). Also using replace for looping is a purpose of replace. The source I provided in my answer takes you to an example on the MDN docs of using replace for exactly this situation.
0

For your example data, you could also first split on a comma and then split on a colon:

let str = "server:all, nit:4545, search:dql has map";
let result = {};
str.split(',').forEach(function(elm) {
  [k, v] = elm.trim().split(':');
  result[k] = v;
});

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.