Paradoxis
Paradoxis

Reputation: 4708

Array to string containing comma's - JavaScript

Ok so I'm writing a script that includes whole sentences, but whole sentences can contain comma's.

Due to the way the script works the array has to be turned into a string at least once. So when that happens the comma's start conflicting with each other once I split the string back into the original values.

I can't quite figure out how to fix this and i've been looking all over with no success so far.

I'm working with chrome plugins, this is a small example of what happens:

var Data = ["This is a normal string", "This string, will cause a conflict.", "This string should be normal"];

// The data gets sent to a background script, in string form and comes back as this
var Data = "This is a normal string, This string, will cause a conflict., This string should be normal";
Data = Data.split(",");

// Results in 4 positions instead of 3
Data = ["This is a normal string", "This string"," will cause a conflict.", "This string should be normal"];

Upvotes: 7

Views: 7854

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39532

You can use JSON.stringify(array) and JSON.parse(json) to make sure that whatever array/object you enter will come back the exact same (and it also works with booleans, integers, floats, etc.):

var data = ["This is a normal string", "This string, will cause a conflict.", "This string should be normal"];

// The data gets sent to a background script, in string form and comes back as this
data = JSON.stringify(data);
console.log(data);
// ["This is a normal string","This string, will cause a conflict.","This string should be normal"] 

data = JSON.parse(data);
console.log(data);
// ["This is a normal string", "This string, will cause a conflict.", "This string should be normal"] 

Upvotes: 3

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

When you call .join() on the array in order to convert it to a string yo ucan specify the delimiter.

For example:

["Hello,","World"].join("%%%"); // "Hello,%%%World"

You can then split it based on "%%%" (.split("%%%")) in order to break it apart again.

That said, if you want to apply an action to each element of an array (every line) you probably do not have to call .join and then .split it again. Instead, you can use array methods, for example:

 var asLower = ["Hello","World"].map(function(line){ return line.toLowerCase(); });
 // as Lower now contains the items in lower case

Alternatively, if your goal is serialization instead of processing - you should not "roll your own" serialization and use the built in JSON.parse and JSON.stringify methods like h2oooooo suggested.

Upvotes: 7

Related Questions