3

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)
2
  • Define societyList like '["Art", "Photography", "Writing"]' then JSON.parse() should work fine Commented Apr 27, 2018 at 6:58
  • @Satpal sir that's the problem how to do that dynamically Commented Apr 27, 2018 at 6:59

4 Answers 4

4

use something like this

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

UPDATE:

After @drinchev suggestion regex used.

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

Sign up to request clarification or add additional context in comments.

5 Comments

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
3

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);

Comments

2

RegExp.match() maybe

 console.log('[Art, Photography, Writing]'.match(/\w+/g))

So match() applies on any string and will split it into array elements.

3 Comments

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.
1

Use replace and 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);

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.