Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string into a map in javascript?

Say, we have a query string that looks like this:

"param1:'test1' && param2:'test2'"

I would like to turn it into an object map, like this:

{param:test1, param2:test2}

How could that be done? This seems like a very common use case.

like image 886
meow Avatar asked Sep 09 '10 08:09

meow


4 Answers

I usually use the "search and don't replace" method:

var ret = {},
    str = "param1:'test1' && param2:'test2'";

str.replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) {
    ret[param] = value;
});

JSON.stringify(ret);
// -> { "param1": "test1", "param2":"test2" }

Example: http://jsfiddle.net/bcJ9s/

like image 133
Andy E Avatar answered Oct 22 '22 09:10

Andy E


As long as it's in that format, i.e. only has string values (and the strings don't contain " && " or colons), you can easily parse it:

var params = theString.split(' && ');
var map = {};
for (var i = 0; i < params.length; i++) {
  var parts = params[i].split(':');
  map[parts[0]] = parts[1].substr(1, parts[1].length - 2);
}

Note that the strings are of course still strings: { param: 'test1', param2: 'test2' }

like image 43
Guffa Avatar answered Oct 22 '22 08:10

Guffa


Use the string.split function to break the string into the parts that you need - something like this...

var input = "param1:'test1' && param2:'test2'";
var entries = input.split(" && ");
var map = {};
var pattern = /'/g;
for(var i=0; i < entries.length; i++){
    var tokens = entries[i].split[":"];
    map[tokens[0]] = tokens[1].replace(pattern, "");
}
like image 1
belugabob Avatar answered Oct 22 '22 08:10

belugabob


Use string processing (As mentioned by @Guffa, it will fail if strings themselves contained && or :):

var str="param1:'test1' && param2:'test2'";
var map={};
var pairs=str.split('&&');
for(i=0, total=pairs.length; i<total; i++) {
  var pair=pairs[i].trim().split(':');
  map[pair[0]]=pair[1].substr(1, pair[1].length-2);
}

Note: trim() is not available on old browsers, you need to add this bit of code before the one above [src]:

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
    };
}
like image 1
aularon Avatar answered Oct 22 '22 09:10

aularon