0

Say I have an array "x", and x shows as [["A", "B", "C"], ["D", "E", "F"]] in the console. How would I convert this to a string verbatim, with all the brackets and quotes?

For example, this should output "[["A", "B", "C"], ["D", "E", "F"]]" (if possible, it would also be nice to add backslashes to the special characters, like "\[\[\"A\", \"B\", \"C\"\], \[\"D\", \"E\", \"F\"\]\]")

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

0

Try JSON.stringify:

var x = [["A", "B", "C"], ["D", "E", "F"]];
var string = JSON.stringify(x);
Rengers
  • 14,911
  • 1
  • 36
  • 54
0

To print it like in your console you can use JSON.stringify().

const arr = [["A", "B", "C"], ["D", "E", "F"]];
const str = JSON.stringify(arr); // [["A","B","C"],["D","E","F"]]

If you also want to add a backslash to every bracket and quotation mark you could loop through every character of the string and add a backslash where it's needed.

// ES6 version
let escapedStr = "";
[...str].forEach(c => {
    if (c === ']' || c === '[' || c === '"') c = `\\${c}`;
    escapedStr += c;
});

console.log(escapedStr) // \[\[\"A\",\"B\",\"C\"\],\[\"D\",\"E\",\"F\"\]\] 

If you do not want use ES6 you can do the same with a simple for loop

for (var i = 0, c=''; c = str.charAt(i); i++) { 
    if (c === ']' || c === '[' || c === '"') c = `\\${c}`;
    escapedStr += c;
}

Edit: Using Regex you can solve the problem in one line

const arr = [["A", "B", "C"], ["D", "E", "F"]];
JSON.stringify(arr).replace(/(\[)|(\])|(\")/g, $1 => `\\${$1}`)