将字符串转换为对象

时间:2015-08-14 12:30:58

标签: javascript node.js

好的,我知道

var str = {}; string.split(' ').forEach(function(val, idx) {str[++idx] = val;});

但是如果字符串是“Hello world”,那么它将返回

["1":"Hello","2":"world","3":"how","4":"r","5":"u"]

我希望它返回

["1":"Hello","2":"world","3":"how r u"]

所以''和“之间的东西是1项,我怎么做呢? 顺便说一句我正在使用node.js

2 个答案:

答案 0 :(得分:0)

不是node.js的大师,所以我不知道在split函数中是否通过正则表达式有一个很好的解决方案,但解决方案可能是编写一个函数来首先拆分原始字符串基于"进入更大的块或者'字符。这将产生一个字符串数组,然后您可以进一步拆分成更小的块。

答案 1 :(得分:0)

谢谢louis on swiftirc #javascript for this

var out = {}; 'this is "a test" with a "random string of words" 34iuv     38vy 3b8u nuhvbe7yvb 73rvy dsuh bue "f34fdvedfg wr edf Fw efwef" efg3f'.match(/\w+|"(.[^"]+)"/g).forEach(function (str, idx) { out[++idx] = str.replace(/^"|"$/g,''); });
console.log(out);

>> {"1":"this","2":"is","3":"a test","4":"with","5":"a","6":"random string of words","7":"34iuv","8":"38vy","9":"3b8u","10":"nuhvbe7yvb","11":"73rvy","12":"dsuh","13":"bue","14":"f34fdvedfg wr edf Fw efwef","15":"efg3f"}