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.
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.
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' }
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/
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");
};
}
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, "");
}