javascript 如何在javascript中将字符串转换为地图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3674763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a string into a map in javascript?
提问by ming yeow
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.
那怎么可能呢?这似乎是一个非常常见的用例。
采纳答案by Andy E
I usually use the "search and don't replace"method:
我通常使用“搜索而不替换”的方法:
var ret = {},
str = "param1:'test1' && param2:'test2'";
str.replace(/(\b[^:]+):'([^']+)'/g, function (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);
}
, param, value) {
ret[param] = value;
});
JSON.stringify(ret);
// -> { "param1": "test1", "param2":"test2" }
Example: http://jsfiddle.net/bcJ9s/
回答by Guffa
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 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 that the strings are of course still strings: { param: 'test1', param2: 'test2' }
请注意,字符串当然仍然是字符串: { param: 'test1', param2: 'test2' }
回答by aularon
Use string processing (As mentioned by @Guffa, it will fail if strings themselves contained &&or :):
使用字符串处理(如@Guffa 所述,如果字符串本身包含&&或,它将失败:):
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "");
};
}
Note: trim()is not available on old browsers, you need to add this bit of code before the one above [src]:
注意:trim()在旧浏览器上不可用,您需要在上面的[src]之前添加这段代码:
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, "");
}
回答by belugabob
Use the string.split function to break the string into the parts that you need - something like this...
使用 string.split 函数将字符串分解成您需要的部分 - 像这样......
##代码##
