How to convert an array like string to array in node.js?
Actually I'm getting the
arraylist from android device in
node.js . But as it's in string form so I wanna convert it into an
array . For that I've referred a lot of similar questions in
SO but none of them were helpful . I also tried to use
JSON.parse() but it was not helpful.
I'm getting societyList in form '[Art, Photography, Writing]'.Thus how to convert this format to an array?
var soc_arr=JSON.parse(data.societyList) console.log(soc_arr.length)
use something like this
var array = arrayList.replace(/^\[|\]$/g, "").split(", ");
After @drinchev suggestion regex used.
regex matches char starts with '[' and ends with ']'
How to convert an array-like string to an array in Node.js?, Use JSON.parse to parse string array to JS array. var timingsAr = '[["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]' JSON.parse(timingsAr); Converting a Byte Array to String with Buffer in Node.JS If you're working with Node.JS, you may have encountered Buffer s which are a way to store binary data as a sequence of its bytes. But what happens when you have serialised it, and you want to convert it back to a String?
This string is not valid JSON since it does not use the
"" to indicate a string.
The best way would be to parse it yourself using a method like below:
let data = '[test1, test2, test3]'; let parts = data .trim() // trim the initial data! .substr(1,data.length-2) // remove the brackets from string .split(',') // plit the string using the seperator ',' .map(e=>e.trim()) // trim the results to remove spaces at start and end console.log(parts);
console.log('[Art, Photography, Writing]'.match(/\w+/g))
split. In addition, use
trim() to remove the trailing and leading whitespaces from the array element.
var str = '[Art, Photography, Writing]'; var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim()); console.log(JSONData);
'["Art", "Photography", "Writing"]'then
JSON.parse()should work fine
- @Satpal sir that's the problem how to do that dynamically
- Even better
list.replace(/^\[|\]$/, "").split( ", " );:)
- @drinchev oups thats not correct can you verify your regex ? im getting a bracket at the last string like ["Art", "Photography", "Writing]"]
- Oops sorry
list.replace(/^\[|\]$/g, "").split( ", " )
- This will break for
["Hello, World", "Hi"]
var array = arrayList.replace(/^\["|"\]$/g, "").split('", "');should fix it (for valid JSON), but as someone pointed out the example string is not valid json
- except in this case you assume each array element is a single word made entirely of ASCII letters. That may be a stretch.
- @Touffy not really much to go in in the question
- I agree. Which is why you shouldn't make assumptions.