Farzin Bidokhti
Farzin Bidokhti

Reputation: 81

How to parse string statement in javascript?

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

Answers (2)

AlenL
AlenL

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

A l w a y s S u n n y
A l w a y s S u n n y

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

Related Questions