-4

I have the following string, containing an array, containing a string:

   '["sgrdalal21"]'

How can I extract the inner string?

7
  • Simple read its first index var str = ["sgrdalal21"][0] Commented Dec 27, 2016 at 11:30
  • Thanx @Satpal, but its giving me only this character [ Commented Dec 27, 2016 at 11:35
  • 2
    Then ["sgrdalal21"] is a string not an array. Test once JSON.parse('["sgrdalal21"]')[0] Commented Dec 27, 2016 at 11:36
  • Yehh, It was string ,Thanx @Satpal. But this Question is not same as you marked Bro! Commented Dec 27, 2016 at 11:40
  • 2
    I wouldn't be surprised that such piece of data is the result of some double encoding. If so, and whenever possible, it'd be better to just fix the code that generates the data rather than adding a workaround on top. Commented Dec 27, 2016 at 12:03

2 Answers 2

2

As '["sgrdalal21"]' as string, JSON.parse() can be used to construct the JavaScript value or object.

var obj = JSON.parse('["sgrdalal21"]');
var str = obj[0]; //Use index to access the element
Sign up to request clarification or add additional context in comments.

Comments

1

What you have is a JSON string:

var json = '["sgrdalal21"]';

You have to parse it as JSON to have an ordinary array. Then you can access the string in the array:

var array, string;
try {
  array = JSON.parse(json);
  string = array[0];
} catch (e) {
  // handle error
}

Remember that whenever you parse JSON strings which you are not sure that are valid (which is usually the case) then you will always have to wrap the JSON.parse() call inside a try/catch block or otherwise your app will crash on invalid JSON. I noticed that people rarely handle JSON.parse() errors in the examples and then people are surprised that their servers are crashing and don't know why. It's because JSON.parse() throws exceptions on bad input and has to be used with try/catch to avoid crashing the entire app:

var array;
try {
  array = JSON.parse(json);
} catch (e) {
  // handle error
}

You can also use tryjson for that:

var array = tryjson.parse(json);

that will do that for you automatically. Now you can use:

var string = array && array[0];

and here the string variable will be undefined if the JSON was invalid or the array did not contain any elements, or will be equal to the inner string, just like in that first example with try/catch above.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.