0

I passing some params from by back to my front through environment params. No problems with strings but I'm getting crazy to do it with an array.

  1. Initial array format = ["one", "two", "three"]
  2. when I pass it to the front, it return "["one", "two", "three"]"
  3. So to solve thats, a little js tricks (.replace(/"/g, "'")) give me that format : "['one', 'two', 'three']"

And now, I would like to transform it to a basic array javascript like this : ['one', 'two', 'three']

Any ideas to solve that (with less code would be great obviously !)

2
  • 1
    You cant use arrays for that: environment variables are strings. allways! What you can do is to "serialize" the array on the backend with <ENV_VAR> = JSON.serialize(...) and "parse" it with JSON.parse(<ENV_VAR>) on the frontend. Commented Oct 21, 2020 at 13:34
  • You can refer to this answer here: stackoverflow.com/questions/9244824/… Seems like the same issue Commented Oct 21, 2020 at 13:36

4 Answers 4

2

You can replace "&quot;" and then split by ",".

let str = "[&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]"
let ret = str.slice(1, -1).replace(/&quot;/g, "").split(",").map(x => x.trim());
console.log(ret);

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

Comments

2

First, unescape the HTML code by passing it through a temporary text area. Second, use JSON.parse() to convert the unescaped String to a JavaScript array.

escaped = "[&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]"

const tmp = document.createElement("textarea");
tmp.innerHTML = escaped;
unescaped = tmp.value;
array = JSON.parse(unescaped);
document.write(array); // "one,two,three"

Comments

1

You can use Javascript eval() function to extract that string into array as follows.

const input = "['one', 'two', 'three']";

console.log(eval(input));

1 Comment

You should avoid using eval, especially if you can simply enter ENV_VAR = "<script> alert () </script>" from outside
0

send data as string from server to client as string

var x = ["one", "two", "three"];
let dataForExchange = x.tostring();

Now when data received at the client parse it into an array again

var xArray = dataForExchange.split(',');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.