I am in a situation in my Ionic project to convert array to string format(array). Here is the example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
should be converted to
var strFruits = "['Banana', 'Orange', 'Apple', 'Mango']";
I can do it using loop and string operation, but there should be an easy way to resolve this.
-
1JSON.stringify maybe?yBrodsky– yBrodsky2018年05月18日 18:46:32 +00:00Commented May 18, 2018 at 18:46
-
Yeah, why not JSON.stringify(fruits)?ricardoorellana– ricardoorellana2018年05月18日 18:47:48 +00:00Commented May 18, 2018 at 18:47
4 Answers 4
Try:
const fruits = ['Banana', 'Apple', 'Orange'];
const format = "['" + fruits.join("', '") + "']";
console.log(format);
// => ['Banana', 'Apple', 'Orange']
Or as suggested in the comments, using JSON.stringify:
const fruits = ['Banana', 'Apple', 'Orange'];
const format = JSON.stringify(fruits);
console.log(format);
// => ["Banana", "Apple", "Orange"]
I personally do not prefer the last one, because you are forced to use double quotes, and the only way to change that is using RegEx.
2 Comments
You can use either use JSON.stringify(fruits) or Just concat "["+fruits.toString()+"]"
Comments
For
const fruits = ["Banana", "Orange", "Apple", "Mango"];
You could do:
console.log(JSON.stringify(fruits));
// ["Banana","Orange","Apple","Mango"]
This returns a string that can be parsed back to JS using JSON.parse() which seems to be exactly what you need
To the scope of your question, this would be valid too:
console.log(`['${fruits.join("', '")}']`);
// ['Banana', 'Orange', 'Apple', 'Mango']
This would return what you asked for with the single quotes, but using JSON.stringify() has the added advantage that the resulting string can always be parsed back (I'ts always valid JSON)
JSON.parse(`['${fruits.join("', '")}']`);
// Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Comments
console.log(JSON.stringify(["Banana", "Orange", "Apple", "Mango"]).replace(/"/g, "'"))
But i think first variant with method "join()" more suitable for this case, because replace() will work with wrong way, if text will contain double quotes.