Reputation: 81
I want to parse this statement in javascript
["TWA"]["STEL"]
and get TWA, STEL value. I guess this is a json and use JSON.parse() method but doesn't work.
Upvotes: 1
Views: 2604
Reputation: 456
That is not a JSON, but you can easily parse it with the pattern matcher:
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);
Upvotes: 3
Reputation: 38552
If it is a string then a simple regex will do the trick.
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(','))
Upvotes: 1