Home > Software engineering >  JavaScript passing String Array to String literal
JavaScript passing String Array to String literal

Time:11-27

I want to pass Array of string values to a string literal as follows

Code :

var array = ['1','2556','3','4','5'];
...
...

var output = `
<scr` `ipt>
    window.stringArray = [`  array  `]
</scr` `ipt>

`

Output :

<script>
    window.stringArray = [1,2556,3,4,5]
</script>

Desired Output:

<script>
    window.stringArray = ['1','2556','3','4','5']
</script>

I've tried to not string the arrays and string it inside the multiline string, but the values are too long for int to handle and it breaks e.g. [888555985744859665555] this will turn into [888555985744859665500] and it's a push on the memory, easy to use string regardless! Next I've tried to use map function within the inline string like this

`[`  array.map(String)  `]`

I can't add any more lines to the output string mentioned above, code can be modified within the one line or added above it!

CodePudding user response:

You can stringify the array. In addition just escape the / instead of using concatenation on the tag name - it's easier to read, and more efficient.

const array = ['1','2556','3','4','5'];

const output = `
  <script>
    window.stringArray = ${JSON.stringify(array)}
  <\/script>
`;

console.log(output);

CodePudding user response:

Why not use JSON.stringify? It works perfectly for your use case!

var array = ['1','2556','3','4','5'];

var output = `
<scr` `ipt>
    window.stringArray = `  JSON.stringify(array)  `;
</scr` `ipt>

`;

console.log(output);

You can read more about the usage of JSON.stringify on MDN.

  • Related