Home > front end >  Javascript : Converting String Into Array Of Strings
Javascript : Converting String Into Array Of Strings

Time:12-22

I have javascript type string -

"[
 'abc',
 'def',
 'ghi'
]"

Above sample is of string type. I want to convert it into array object -> Array of strings ->

[
'abc',
     'def',
     'ghi'
]

I tried with map function - array.map(strArray,string) but got syntax error as strArray is not itself a array , its string.

CodePudding user response:

If the strings are valid strings according to JavaScript (quotes escaped properly, delimited by backticks, single quotes, double quotes, etc) you can eval the stringified array.

arrayOfStrings = eval(strArray);

This evaluates the string as a JavaScript expression. Note that the eval function is sometimes frowned upon because it can lead to misinterpretations.

If your stringified array is a valid JSON string, you can JSON.parse it instead:

arrayOfStrings = JSON.parse(strArray);

There are a few restrictions on the applicability of this method; for instance the strings must be delimited with double quotes as that is the proper JSON format. There are other restrictions as well.

For very, very general cases (such as if your array does not use quotes: [abc, blah blah, cd]) you will need to capture the strings. Assuming that the strings do not contain commas, you can do this:

const parseStringArray = l => l.replace(/\n|\[|\]/g, '').split(',')

This solution makes the following assumptions: the strings contain no commas (see above), no newlines, no square brackets, are separated by commas, and the stringified list is in the following format:

<open square brace><zero or more newlines><zero or more of (<string which can contain any character except comma, newline, open square brace or close square brace><zero or more newlines>)><close square brace>

(sorry, I'm not very familiar with regex but if someone could provide me with a regex, that would be very helpful.)

CodePudding user response:

let x = "[1,2,3]"

x = JSON.parse(x)
  • Related