Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Code:

var soc_arr=JSON.parse(data.societyList)
            console.log(soc_arr.length)
like image 720
anonymous Avatar asked Jun 12 '26 10:06

anonymous


2 Answers

use something like this

var array = arrayList.replace(/^\[|\]$/g, "").split(", ");

UPDATE:

After @drinchev suggestion regex used.

regex matches char starts with '[' and ends with ']'

like image 111
Panos K Avatar answered Jun 14 '26 00:06

Panos K


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);
like image 25
Bellian Avatar answered Jun 13 '26 22:06

Bellian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!