Vaishnavi Dongre
Vaishnavi Dongre

Reputation: 259

Converting array inside a string to an array

I have a response which contains an array which is present inside string(""). What I need I just the array. How do I get rid of the quotes?

I tried JSON.parse(). It gave me error message

SyntaxError: Unexpected token ' in JSON at position 1

What I have is as follows:

email_id: "['[email protected]', '[email protected]']"

What I need is as follows:

email_id: ['[email protected]', '[email protected]']

This is a key which a part of a large response I am getting from backend in my angular 7 app.

Upvotes: 3

Views: 1279

Answers (2)

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

You have to send in backend the format with double quotes instead of one quotes or in front just replace quotes ' with double quotes " inside your array , otherwise the parse will fail ,

see below snippet :

let json = {
  email_id:  "['[email protected]', '[email protected]']"
}
json.email_id = json.email_id.replace(/'/g,"\"");
console.log(JSON.parse(json.email_id));

Upvotes: 1

Mahesh
Mahesh

Reputation: 1635

Below solution will work for your case provided the strings does not contain /'

var a = "['[email protected]', '[email protected]', '[email protected]']";
a = a.replace(/'/g, '"');
var result = JSON.parse(a);

Considering its an email data, there's no possibility of having that escape character sequence

Upvotes: 4

Related Questions