1

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.

2
  • 2
    No it is not JSON. A regex would work. If you want to use JSON.parse you need JSON.parse('["TWA"]["STEL"]'.replace('][',',')) Commented Sep 29, 2018 at 14:13
  • This is not valid JSON and cannot be parsed as such. You could use regular expressions as a quick way of lexing this. Or, you could split on "[" (or "]") and remove the unwanted characters from the parts. Commented Sep 29, 2018 at 14:16

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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(','))

5 Comments

Or shorter: JSON.parse('["TWA"]["STEL"]'.replace('][',','))
For this ["TWA."]["STEL"] that approach doesn't work.
@mplungjan Yes sir, totally agreed with you :) May I edit my answer?
@Ele agree. but OP posted string like ["TWA"]["STEL"] that's why I used that
Just leave my comment. No need to add it to your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.