我想在javascript中解析此语句
["TWA"]["STEL"]
并获得TWA,STEL值。我想这是一个 json 并使用 JSON.parse(( 方法但不起作用。
这不是 JSON,但您可以使用模式匹配器轻松解析它:
https://jsfiddle.net/60dshj3x/
let text = '["TWA"]["STEL"]'
let results = text.match(/["(.*)"]["(.*)"]/)
// note that results[0] is always the entire string!
let first = results[1]
let second = results[2]
console.log("First: " + first + "nSecond: " + second);
如果它是一个字符串,那么一个简单的正则表达式就可以了。
const regex = /["(w+)"]/gm;
const str = `["TWA"]["STEL"]`;
let m;
let words = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
if(groupIndex===1)words.push(match)
});
}
console.log(words.join(','))