循环字符串获取键和值使用正则表达式键匹配Javascript

时间:2017-06-16 09:24:40

标签: javascript json regex

我有一个像

这样的字符串
> var temp =
> "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green),"

有关信息,此字符串由kibana自动生成(我通过url恢复)。

我的问题是: 有任何解决方案可以从此字符串中提取键和值,并在数组或对象中获取结果,如下所示:

>  var result = { 
>                  "alias" : "!n",
>                  "apply" : "!t",
>                  "disabled" : "!f",
>                  "key": "stockInfo.raw",
>                  "negate": "!f",
>                  "value": "green",  
>               }

由于

3 个答案:

答案 0 :(得分:2)

我认为您正在搜索这样的内容:

var meta = "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green),"

var result = {}

meta.substr(0, meta.length - 2).substr(5).split(',').forEach(function(item) {
  var split = item && item.split(':')
  if (split.length) {
    result[split[0]] = split[1];
  }
})

console.log(result)

,字符拆分字符串,然后按:拆分以识别对象的键和值

答案 1 :(得分:1)

与其他相同,但有一些es6语法:D



const result = document.getElementById("result");
const input = document.getElementById("input");

// string: data from url, return only the portion from the parenthesis
const extract_meta_values = string => {
 const EXTRACTOR = /^meta\(([^\)]+)\)/g;
 return EXTRACTOR.exec(string)[1];
}

// string: is a string of key:values separated by a comma
const meta_values_to_array_of_objects = string => string.split(',').map( tuple => {
  const [key, value] = tuple.split(':');
  return { [key]: value };
});

const meta_values = extract_meta_values(input.value);
const final = meta_values_to_array_of_objects(meta_values);

// print out
result.innerText = JSON.stringify(final, null, 2);

pre {
  display: block;
  border: 1px solid darkgray;
}

<p>
<input value="meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green)," id=input />
</p>

<pre id=result></pre>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在括号内的子串,用逗号分割,循环,用冒号分割并添加到对象。

&#13;
&#13;
var temp = "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green)";
var t = {};
temp
  .substr(temp.indexOf("(") + 1, temp.indexOf(")") - temp.indexOf("(") - 1)
  .split(",")
  .forEach(function(a) {
    var b = a.split(":");
    t[b[0]] = b[1];
  });
console.log(t);
&#13;
&#13;
&#13;